好的。我会简短介绍一下。为什么这不起作用?为什么泛型方法不能用于继承和接口?
//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