【问题标题】:The type 'T' cannot be used as type parameter 'T' in the generic type or method类型“T”不能用作泛型类型或方法中的类型参数“T”
【发布时间】:2018-10-12 00:54:01
【问题描述】:

我有以下方法:

protected T AttachComponent<T>(){
    T gsComponent = gameObject.GetComponent<T>();
    if(gsComponent == null){
        gsComponent = gameObject.AddComponent<T>();
    }
    return gsComponent;
}

AddComponent 行我收到以下错误:

类型“T”不能用作泛型类型或方法“GameObject.AddComponent()”中的类型参数“T”。 没有从“T”到“UnityEngine.Component”的装箱转换或类型参数转换。

我不确定我能做些什么来修复这个错误,为什么我不能这样做?

【问题讨论】:

标签: c# unity3d


【解决方案1】:

问题在于AddObject 方法返回Component。您需要告诉编译器您的 T 实际上是一种 Component。

为您的方法附加一个通用约束,以确保您的 Ts 是 Components

protected void AttachComponent<T>() where T : Component
{
    // Your code.
}

【讨论】:

  • 这给了我这个:'GameObject' 不是一个有效的约束。用作约束的类型必须是接口、非密封类或类型参数。
  • @GetOffMyLawn 对不起,我误读了你的问题。我在此期间更新了代码以澄清我的答案。请注意,约束现在位于Component,而不是GameObject(我的错误)
  • 没问题!您能否解释一下“where”部分的用途?
  • 这是一个generic constraint。基本上,它告诉编译器T 将继承或实现Component,因此编译器可以将其视为Component。您可以应用许多其他限制 - 检查链接:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多