2016-07-30 28 views
0

由於不熟悉System.Reflection,我想知道是否有方法可以從某個自定義類繼承的項目中返回類。System.Reflection =>查找自定義類

自定義類只是一個樣本類

public class Parent 
{ 
    public Parent() { } 
} 

繼承類同樣只是一個樣本的類集合

public class ParentA : Parent 
{ 
    /*code*/ 
} 

public class Something 
{ 
    /*code*/ 
} 

public class SneakyParent : Parent 
{ 
    /*code*/ 
} 

的System.Reflection代碼我已經試過Thi s當前在控制檯應用程序寫的,但最終會輸出到一個數組或列表

class Program 
{ 
    static void Main(string[] args) 
    { 
     Assembly assem = typeof(Parent).Assembly; 
     foreach (var type in assem.GetTypes()) 
     { 
      Console.WriteLine($"Parent \"{type.Name}\" found!"); 
     } 
     Console.ReadLine(); 
    } 
} 

運行這是輸出我得到的代碼之後:

Parent "Parent" found! 
Parent "Program" found! 
Parent "ParentA" found! 
Parent "Something" found! 
Parent "SneakyParent" found! 

隨着幾聲「嗯。 ..我想知道「嘗試我仍然無法弄清楚如何返回正確的輸入,而不是如何返回類。理想情況下,我希望輸出是...

Parent "Parent A" found! 
Parent "SneakyParent" found! 

...以及將這些類返回到列表或數組。

+0

你想使用[Type.IsSubclassOf](https://msdn.microsoft.com/en-us/library/system.type.issubclassof(V = vs.110)的.aspx)方法。 –

+0

這解決了找到正確類的問題!非常感謝Michael Liu! –

回答

0
Assembly assem = typeof(Parent).Assembly; 
foreach (var type in assem.GetTypes().Where(x => x.IsSubclassOf(typeof(Parent)))) 
{ 
    Console.WriteLine($"Parent \"{type.Name}\" found!"); 
} 
Console.ReadLine(); 
+0

謝謝!當我走到我要去的地方時,我會標記爲答案! –