问题描述
- [cs] 如何在一个函数体内给泛型赋值?
-
例如public UnityEngine.Component GetComponent(System.Type type) {} // metadata token 060018FE public T GetComponent<T>() where T : UnityEngine.Component { return (T)(this.GetComponent(typeof(T)) as T); }
怎么反推上面2个函数
public UnityEngine.Component GetComponent(System.Type type) { //这里怎么调用 T GetComponent<T>()? type赋值<T> }
解决方案
public UnityEngine.Component GetComponent(System.Type type) {
return GetComponent<UnityEngine.Component>();
}
解决方案二:
最好是泛型调用非泛型。
如果反过来,用类型参数来调用泛型,那么就要用到反射,效率不高:
public UnityEngine.Component GetComponent(System.Type type)
{
var methodInfo = this.GetType().GetMethod("GetComponent", Type.EmptyTypes);
var methodInfo_t = methodInfo.MakeGenericMethod(type);
return methodInfo_t.Invoke(this, null) as UnityEngine.Component;
}
时间: 2024-11-05 12:09:51