获取基本类型的所有后代? [英] Get all last descendants of a base type?
本文介绍了获取基本类型的所有后代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果这是我拥有的继承层次结构,
If this is the inheritance hierarchy I have,
class Base
{
}
class Derived1 : Base
{
}
class Derived1A : Derived1
{
}
class Derived1B : Derived1
{
}
class Derived2 : Base
{
}
我需要一种机制来查找特定程序集中位于继承树末尾的所有Base
类的子类型.换句话说,
I need a mechanism to find all the sub types of Base
class in a particular assembly which are at the end of the inheritance tree. In other words,
SubTypesOf(typeof(Base))
应该给我
-> { Derived1A, Derived1B, Derived2 }
推荐答案
这就是我提出的.不知道是否存在一些更优雅/有效的解决方案.
This is what I have come up with. Not sure if some more elegant/efficient solutions exist..
public static IEnumerable<Type> GetLastDescendants(this Type t)
{
if (!t.IsClass)
throw new Exception(t + " is not a class");
var subTypes = t.Assembly.GetTypes().Where(x => x.IsSubclassOf(t)).ToArray();
return subTypes.Where(x => subTypes.All(y => y.BaseType != x));
}
出于完整性考虑,我会在此处
And for sake of completeness, I will repost the answer for direct descendants given here
public static IEnumerable<Type> GetDirectDescendants(this Type t)
{
if (!t.IsClass)
throw new Exception(t + " is not a class");
return t.Assembly.GetTypes().Where(x => x.BaseType == t);
}
这篇关于获取基本类型的所有后代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文