好的。我會簡短介紹一下。爲什麼這不起作用?爲什麼泛型方法不能用於繼承和接口?
//Find<T> returns the T object with a given name
//Not a true method, but that's simplier for the example.
Warrior conan = Find<Warrior> ("Conan");
//Debug.Log is just printing the results
Debug.Log (conan is Warrior); //True
Debug.Log (conan is Character); //True, Warrior extends Character
Character other = Find<Character> ("Conan"); // Null, Why ?
我猜一般的c#方法在IL中是非常不同的,這就是爲什麼不起作用。但它很煩人。我做錯了什麼?有沒有辦法繞過這個?
編輯:
事實上,我的方法有點不同。我正在使用MVC,我想查找對應於模型的視圖。
public ElementView<E> Find<E> (E model) {
ElementView<E>[] tab = gameBoardView.transform.GetComponentsInChildren<ElementView<E>>();
foreach (ElementView<E> el in tab)
if (EqualityComparer<E>.Default.Equals(el.model, model))
return el;
return null;
}
我用它是這樣的:
ElementView<Warrior> w = Find<Warrior> (myCharacter); // good if my character is a warrior
ElementView<Character> c = Find<Character> (myCharacter); // null
添加Find的代碼將有所幫助。 –
請顯示'Find'方法的來源。 – dasblinkenlight
如何提出一個好問題:[問]以及如何提供良好的示例代碼:[mcve] – AndyJ