码迷,mamicode.com
首页 > Windows程序 > 详细

C# 获取DLL中需要的接口类

时间:2019-06-18 13:56:08      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:for   var   man   return   ini   inter   direct   本地   typeof   

[ 需求 ]

使用反射,循环本地DLL文件,获取实现了所需接口的类,并实例化。

Loop local dll files by reflection library and assembly library to find all the classes that implement certain interface and create instances for them.

二话不说,先上代码。

Talk is cheap. Show me the code.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Reflection;
 6 
 7 namespace InterfaceClassLoader
 8 {
 9     public class Loader
10     {
11 
12         private List<IMyInterface> myInstanceList;
13         private void Initialize()
14         {
15 
16             try
17             {
18                 var type= typeof(IMyInterface);
19                 myInstanceList= GetAllAssemblies().
20                     SelectMany(a => a.GetTypes()).
21                     Where(t => !t.IsInterface && type.IsAssignableFrom(t)).
22                     Select(t => (IMyInterface)Activator.CreateInstance(t)).ToList();
23             }
24             catch (Exception ex)
25             {}
26         }
27 
28 
29         private List<Assembly> GetAllAssemblies()
30         {
31             var folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
32             var allAssemblies = new List<Assembly>();
33             Directory.GetFiles(folderPath,"*.dll").ToList().ForEach(f => 
34             {
35                 allAssemblies.Add(Assembly.LoadFile(f));
36             });
37 
38 
39             var filteredAssembly = allAssemblies.FindAll(a => a.FullName.Contains("MyMark"));
40             return filteredAssembly;
41         }
42 
43     }      
44 
45 }

 

C# 获取DLL中需要的接口类

标签:for   var   man   return   ini   inter   direct   本地   typeof   

原文地址:https://www.cnblogs.com/jiceberg420/p/11044688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!