Get all last descendants of a base type?

↘锁芯ラ 提交于 2020-01-25 06:31:09

问题


This question is an opposite of How to find types that are direct descendants of a base class?

If this is the inheritance hierarchy I have,

class Base
{

}



class Derived1 : Base
{

}

class Derived1A : Derived1
{

}

class Derived1B : Derived1
{

}



class Derived2 : 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)) 

should give me

-> { Derived1A, Derived1B, Derived2 }

回答1:


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


来源:https://stackoverflow.com/questions/18487904/get-all-last-descendants-of-a-base-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!