这个问题与How to find types that are direct descendants of a base class?
相反如果这是我拥有的继承层次结构,
class Base
{
}
class Derived1 : Base
{
}
class Derived1A : Derived1
{
}
class Derived1B : Derived1
{
}
class Derived2 : Base
{
}
我需要一种机制来查找特定程序集中位于继承树末尾的Base
类的所有子类型。换句话说,
SubTypesOf(typeof(Base))
应该给我
-> { Derived1A, Derived1B, Derived2 }
答案 0 :(得分:1)
这就是我想出的。不确定是否存在一些更优雅/更有效的解决方案..
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));
}
为了完整起见,我将重新给出直接后代的答案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);
}