C# - 根据参数返回类型的通用方法

标签 c# generics methods

我有这个通用方法:

    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);

    }

enter image description here

我这样调用它:

var myVar = UI_POINTS.FindObject("Score", typeof(Text));

enter image description here

但我给出了以下错误:

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/

相关文章:

.net - 具有 byref 参数覆盖的 F# 方法

c# - 如何将多个 TextReader 串在一起?

c# - 如何将 foreach 循环转换为 lambda 表达式

c# - Directory.EnumerateFiles 搜索模式不适用于文件共享

C# - 代码有什么问题(泛型、静态方法等)

c# - 动态替换 C# 方法的内容?

c# - C# 中未使用的 "using"指令的性能影响

C# 类型推断 : How to properly define constraints on method?

c# - 如何使用反射确定基类的泛型参数

javascript - 是否可以在 Java6 1.6 脚本引擎中从 JavaScript 调用 Java 方法?