搜索程序集的所有子类型? [英] Search an assembly for all child types?
问题描述
我想找到从基本/接口继承的所有类型。任何人都有一个好的方法来做到这一点?想要吗?
我知道这是一个奇怪的请求,但它是我一直在玩的无所不在的。
使用Assembly.GetTypes()获取所有类型,并使用Type.IsAssignableFrom()来检查继承。让我知道,如果你需要代码 - 以及你是否使用.NET 3.5。 (很多像这样的反射任务用LINQ to Objects更简单。)
编辑:根据请求,这里有一个例子 - 它找到 mscorlib
,它实现 IEnumerable
。注意,当基本类型是通用的时,生活有点困难...
使用System;
using System.Collections;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
装配体= typeof(string).Assembly;
Type target = typeof(IEnumerable);
var types = assembly.GetTypes()
.Where(type => target.IsAssignableFrom(type));
foreach(类型类型)
{
Console.WriteLine(type.Name);
}
}
}
I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?
I know this is a strange request but its something I'm playing with none-the-less.
Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)
EDIT: As requested, here's an example - it finds everything in mscorlib
which implements IEnumerable
. Note that life is somewhat harder when the base type is generic...
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
Assembly assembly = typeof(string).Assembly;
Type target = typeof(IEnumerable);
var types = assembly.GetTypes()
.Where(type => target.IsAssignableFrom(type));
foreach (Type type in types)
{
Console.WriteLine(type.Name);
}
}
}
这篇关于搜索程序集的所有子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!