我正在嘗試做一些事情,但我不知道如何調用/命名此函數,並且我在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;
}
編譯器會在最後一行,如果我嘗試投child
到T
明確地,它抱怨多一些。我該怎麼做,請告知。
但是你需要第二和第三行嗎?如果找不到任何內容,FirstOrDefault將返回null,如果沒有發現任何內容,我希望從我的方法返回null。 –
@DreadBoy是的,你可以刪除這些行,如果你想返回null。 – Valentin
太好了,我接受你的答案!謝謝。 –