c# - 获取基本类型的所有最后后代?

标签 c# inheritance reflection types descendant

这个问题与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 }

最佳答案

这就是我想出来的。不确定是否存在一些更优雅/高效的解决方案..

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);
}

关于c# - 获取基本类型的所有最后后代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18487904/

相关文章:

javascript - 如何在Javascript中继承静态和非静态属性?

Java反射和接口(interface)作为参数

java - 当我知道该类时如何正确调用方法?

c# - 在 C# 中测试对象是否为字典

c# - C# 中处理线程状态的模式

c# - 使用超时终止进程和任何子进程

C# MySql 创建用户

c# - 在 C#/.NET 4.0 中填充和使用动态类

C++多级继承不起作用

java - 从派生类调用构造函数