本文介绍了如何找到所有在大会,从一个特定类型的C#继承的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么都从一个特定的其他类型的继承类型的集合?

How do you get a collection of all the types that inherit from a specific other type?

推荐答案

是这样的:

public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
{
    return assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t));
}

如果你需要处理的仿制药,是可以获得有点麻烦(例如通过在开放列表与LT;&GT; 类型,但希望取回从派生的类型列表与LT; INT&GT; )。否则,它很简单,但:)

If you need to handle generics, that gets somewhat trickier (e.g. passing in the open List<> type but expecting to get back a type which derived from List<int>). Otherwise it's simple though :)

如果您要排除的类型本身,你可以这样做很容易就够了:

If you want to exclude the type itself, you can do so easily enough:

public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
{
    return assembly.GetTypes().Where(t => t != baseType && 
                                          baseType.IsAssignableFrom(t));
}

请注意,这也将让您指定的接口,并找到所有实现它的类型,而不是仅仅使用类为 Type.IsSubclassOf 一样。

Note that this will also allow you to specify an interface and find all the types which implement it, rather than just working with classes as Type.IsSubclassOf does.

这篇关于如何找到所有在大会,从一个特定类型的C#继承的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 19:54