2013-08-28 31 views
1

這個問題的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 } 

回答

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

什麼Derived1直接後裔的答案嗎? – I4V

+0

@ I4V Derived1不在層次結構樹的末尾。它有孩子。今天我有一個特殊的要求,我想要最小的地方:) – nawfal

相關問題