C#中獲取某個接口的所有子類的集合

近日有朋友在論壇(.Net技術論壇)中問到,如何獲取實現某個接口的所有類。這個問題是所有大型項目中經常遇到的問題,有經驗的程序員可能會在開發的時候寫好配置文檔,以方便以後使用,而對於第三方開發的dll或程序則無此遍歷了,那我們該怎麼辦呢?

這裏我提供了一種基於msdn上對FindInterfaces的說明來解決這個問題。

思路如下:

首先載入一個類庫文件,

//載入dll文件並獲取屬性
Assembly assembly = Assembly.LoadFile(dllFile); 
//取出所有類型集合
Type[] types = assembly.GetTypes();

接下來遍歷所有類型,爲了找到,接口類型。再獲取接口的實現類。

 1: //遍歷類型
 2: foreach (Type type in types) 
 3: { 
 4: //找到接口
 5: if (type.GetInterface("InterfaceName") != null && !type.IsAbstract) 
 6: { 
 7: // 這個type就是子類了。
 8: type.GetConstructor(Type.EmptyTypes).Invoke(null); 
 9: } 
 10: }

至此,我們的問題得以解決。

以下是結合msdn得出一個實例:


using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Reflection; 
namespace TestGetInterface 
{ 
class Program 
 { 
publicstaticbool MyInterfaceFilter(Type typeObj, Object criteriaObj) 
 { 
if (typeObj.ToString() == criteriaObj.ToString()) 
returntrue; 
else
returnfalse; 
 } 
staticvoid Main(string[] args) 
 { 
 Assembly assembly = Assembly.LoadFile(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll");//你的loadfile
 Type[] types = assembly.GetTypes(); 
 TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); 
//String[] myInterfaceList = new String[2] 
// {"System.Collections.IEnumerable", 
// "System.Collections.ICollection"};
 String[] myInterfaceList = new String[1] 
 { 
 "System.Collections.ICollection"};//支持ICollection
foreach (Type type in types) 
 { 
for (int index = 0; index < myInterfaceList.Length; index++) 
 { 
 Type[] myInterfaces = type.FindInterfaces(myFilter, 
 myInterfaceList[index]); 
if (myInterfaces.Length > 0) 
 { 
 Console.WriteLine("\n{0} implements the interface {1}.", 
 type, myInterfaceList[index]); 
for (int j = 0; j < myInterfaces.Length; j++) 
 Console.WriteLine("Interfaces supported: {0}.", 
 myInterfaces[j].ToString()); 
 } 
//else
// Console.WriteLine(
// "\n{0} does not implement the interface {1}.",
// type, myInterfaceList[index]);
 } 
 } 
 Console.ReadLine(); 
 } 
 } 
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章