类型"T"不能用作通用类型或方法中的类型参数"T" [英] The type 'T' cannot be used as type parameter 'T' in the generic type or method
问题描述
我有以下方法:
protected T AttachComponent<T>(){
T gsComponent = gameObject.GetComponent<T>();
if(gsComponent == null){
gsComponent = gameObject.AddComponent<T>();
}
return gsComponent;
}
在AddComponent
行上,出现以下错误:
On the AddComponent
line I am getting the following error:
类型"T"不能用作通用类型或方法"GameObject.AddComponent()"中的类型参数"T". 没有从"T"到"UnityEngine.Component"的装箱转换或类型参数转换.
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'.
我不确定该如何解决该错误,为什么我不能这样做?
I am not sure what I can do to fix this error, why Can I not do this?
推荐答案
问题是 AddObject 方法将返回组件.您需要告诉编译器您的T实际上是一种Component.
The issue is that the AddObject method returns a Component. You need to tell the compiler that your T is actually a type of Component.
为您的方法附加一个通用约束,以确保您的T
是Component
s
Attach a generic constraint to your method, to ensure that your T
s are Component
s
protected void AttachComponent<T>() where T : Component
{
// Your code.
}
这篇关于类型"T"不能用作通用类型或方法中的类型参数"T"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!