1

この質問は、 「基本クラスの直接の子孫である型を見つける方法は?」の反対です。

これが私が持っている継承階層である場合、

class Base
{

}



class Derived1 : Base
{

}

class Derived1A : Derived1
{

}

class Derived1B : Derived1
{

}



class Derived2 : Base
{

}

Base継承ツリーの最後にある特定のアセンブリ内のクラスのすべてのサブタイプを見つけるメカニズムが必要です。言い換えると、

SubTypesOf(typeof(Base)) 

私に与えるべきです

-> { Derived1A, Derived1B, Derived2 }
4

1 に答える 1

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

完全を期すために、ここで与えられた直系の子孫の答えを再投稿します

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);
}
于 2013-08-28T12:27:41.687 に答える