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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM