您的位置:首页 > 编程语言 > C#

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

2013-07-08 10:31 323 查看
近日有朋友在论坛(.Net技术论坛)中问到,如何获取实现某个接口的所有类。这个问题是所有大型项目中经常遇到的问题,有经验的程序员可能会在开发的时候写好配置文档,以方便以后使用,而对于第三方开发的dll或程序则无此遍历了,那我们该怎么办呢?这里我提供了一种基于msdn上对FindInterfaces的说明来解决这个问题。思路如下:首先载入一个类库文件,
//载入dll文件并获取属性
Assembly assembly = Assembly.LoadFile(dllFile);
//取出所有类型集合
Type[] types = assembly.GetTypes();


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre {margin: 0em;}
.csharpcode .rem {color: #008000;}
.csharpcode .kwrd {color: #0000ff;}
.csharpcode .str {color: #006080;}
.csharpcode .op {color: #0000c0;}
.csharpcode .preproc {color: #cc6633;}
.csharpcode .asp {background-color: #ffff00;}
.csharpcode .html {color: #800000;}
.csharpcode .attr {color: #ff0000;}
.csharpcode .alt
{
background-color: #f4f4f4;
100%;
margin: 0em;
}
.csharpcode .lnum {color: #606060;}接下来遍历所有类型,为了找到,接口类型。再获取接口的实现类。
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();
}
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: