简体   繁体   English

类型“ T”不能用作通用类型或方法中的类型参数“ T”

[英]The type 'T' cannot be used as type parameter 'T' in the generic type or method

I have the following method: 我有以下方法:

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

On the AddComponent line I am getting the following error: AddComponent行上,出现以下错误:

The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. 类型“ T”不能用作通用类型或方法“ GameObject.AddComponent()”中的类型参数“ T”。 There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'. 没有从“ T”到“ UnityEngine.Component”的装箱转换或类型参数转换。

I am not sure what I can do to fix this error, why Can I not do this? 我不确定该如何解决此错误,为什么我不能这样做?

The issue is that the AddObject method returns a Component . 问题是AddObject方法返回一个Component You need to tell the compiler that your T is actually a type of Component. 您需要告诉编译器您的T实际上是Component的一种。

Attach a generic constraint to your method, to ensure that your T s are Component s 将通用约束附加到您的方法,以确保TComponent

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型“ XXX”不能用作通用类型或方法中的类型参数“ T” - The type 'XXX' cannot be used as type parameter 'T' in the generic type or method 类型&#39;&#39;不能在通用类型或方法中用作类型参数&#39;T&#39; - The type '' cannot be used as type parameter 'T' in the generic type or method 当类型已知时,类型&#39;T&#39;不能用作泛型类型或方法错误中的类型参数 - The type 'T' cannot be used as type parameter in the generic type or method error when type is known 该类型不能在泛型类型或方法'BaseController <T>'中用作类型参数'T'。没有隐含的参考 - The type cannot be used as type parameter 'T' in the generic type or method 'BaseController<T>'. There is no implicit reference 泛型:“相机”类型不能用作泛型类型中的类型参数“T” - Generics: The type 'Camera' cannot be used as type parameter 'T' in the generic type 类型X不能用作通用类型Y中的类型参数T - The type X cannot be used as type parameter T in the generic type Y Xamarin / Realm-该类型不能用作通用类型或方法中的类型参数“ T” - Xamarin/Realm - The type cannot be used as type parameter 'T' in the generic type or method 类型&#39;System.Windows.Forms.GroupBox&#39;不能在泛型类型或方法中用作类型参数&#39;T&#39; - The type 'System.Windows.Forms.GroupBox' cannot be used as type parameter 'T' in the generic type or method 类型 &#39;&#39; 不能用作泛型类型或方法 &#39;&#39; 中的类型参数 &#39;T&#39;。 没有从 &#39;&#39; 到 &#39;&#39; 的隐式引用转换 - The type '' cannot be used as type parameter 'T' in the generic type or method ''. There is no implicit reference conversion from '' to '' 通用方法-类型不能用作类型参数 - Generic method - Type cannot be used as Type Parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM