温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中获取某个接口的所有子类的集合

发布时间:2020-06-30 11:11:56 来源:网络 阅读:1996 作者:OH51888 栏目:编程语言

近日有朋友在论坛(.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(); 
 } 
 } 
 }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI