近日有朋友在论坛(.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();

}

}

}