【问题标题】:Get all last descendants of a base type?获取基本类型的所有最后后代?
【发布时间】:2013-08-31 12:38:38
【问题描述】:

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

【问题讨论】:

    标签: c# inheritance reflection types descendant


    【解决方案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);
    }
    

    【讨论】:

    • Derived1 怎么样?
    • @I4V Derived1 不在层次结构树的末尾。它有孩子。我今天有一个特殊要求,我想要最年轻的很多:)
    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2011-10-26
    • 2020-01-25
    • 2018-02-28
    相关资源
    最近更新 更多