2016-06-12 90 views
2

我正在嘗試做一些事情,但我不知道如何調用/命名此函數,並且我在Google上找不到任何有用的東西。我有基類在父類的列表中返回子類的實例的泛型方法

public class Parent{/*some code here*/} 

和子類

public class Child1:Parent{/*more code*/} 
public class Child2:Parent{/*expended behaviour*/} 

如果我創建

List<Parent> children = new List<Parent>(); 

我可以高興地把所有的孩子在該列表中,但我有麻煩編寫通用方法來檢索他們。事情是這樣的:

public T GetChild<T>() 
{ 
    var child = children.Find(c => c.GetType() == typeof(T)); 
    if (child == null) 
     return default(T); 
    return child; 
} 

編譯器會在最後一行,如果我嘗試投childT明確地,它抱怨多一些。我該怎麼做,請告知。

回答

3

您可以使用OfType方法獲取特定類的所有實例。 children.OfType<T>();然後,如果您需要單個實例,則可以使用FirstFirstOrDefault()方法。

public T GetChild<T>() 
    { 
     var child = children.OfType<T>().FirstOrDefault(); 
     if (child == null) 
      return default(T); 
     return child; 
    } 

或者只是

public T GetChild<T>() 
{ 
    return children.OfType<T>().FirstOrDefault(); 
} 
+0

但是你需要第二和第三行嗎?如果找不到任何內容,FirstOrDefault將返回null,如果沒有發現任何內容,我希望從我的方法返回null。 –

+0

@DreadBoy是的,你可以刪除這些行,如果你想返回null。 – Valentin

+0

太好了,我接受你的答案!謝謝。 –

0

您可以檢查父的在你需要使用,找出自己的類型的多個孩子面前類別「爲」關鍵字。例如:

if(child是Child1)return Child1; else return Child2;

+0

這會打敗泛型函數的目的,不是嗎?想象一下,我有10個子類,如果子句我需要10個子類。或者想象我稍後再添加一個孩子,並忘記這條線。無論我添加多少新的子類,我想要編寫的通用函數都將完成其工作。 –