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

Posted jiceberg420

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 获取DLL中需要的接口类相关的知识,希望对你有一定的参考价值。

[ 需求 ]

使用反射,循环本地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中需要的接口类的主要内容,如果未能解决你的问题,请参考以下文章

C#开发的OpenRA动态加载插件DLL里的类实现

C#开发的OpenRA动态加载插件DLL里的类实现

C#:MWArray 和获取类的实例

C# 动态调用DLL库

C#调用C++ DLL类方法

c#如何将一个类库打包成两个dll