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 
public static bool MyInterfaceFilter(Type typeObj, Object criteriaObj) 
if (typeObj.ToString() == criteriaObj.ToString()) 
return true
else
return false
static void 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(); 
 
 
}

from:http://blog.sina.com.cn/s/blog_6f7b41640101bnyr.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值