我有这个通用方法:
public static T FindObject<T> (this GameObject gameObject, string objectName, Type type)
{
var ret = gameObject.GetComponentsInChildren(type).Where(w => w.name == objectName).First();
return (T)Convert.ChangeType(ret, type);
}
我这样调用它:
var myVar = UI_POINTS.FindObject("Score", typeof(Text));
但我给出了以下错误:
The type arguments for method 'ExtensionMethods.FindObject(GameObject, string, Type)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
他为什么不理解方法调用?
提前谢谢你。
最佳答案
编译器不知道 T
是什么,因为你没有告诉它,它也不能从方法的参数中推断出来。您已经将 Type
对象作为参数传递给它,但是编译器应该如何知道它指的是 T
?
事实上,我也在假设这一点——而且我无法从您的代码中确定这是否是意图。如果是,试试这个:
public static T FindObject<T> (this GameObject gameObject, string objectName)
{
var type = typeof(T);
var ret = gameObject.GetComponentsInChildren(type).Where(w => w.name == objectName).First().gameObject;
return (T)Convert.ChangeType(ret, type);
}
其次是:
var myVar = UI_POINTS.FindObject<Text>("Score");
关于C# - 根据参数返回类型的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489578/