类型"T"不能用作通用类型或方法中的类型参数"T" [英] The type 'T' cannot be used as type parameter 'T' in the generic type or method

查看:355
本文介绍了类型"T"不能用作通用类型或方法中的类型参数"T"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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.

为您的方法附加一个通用约束,以确保您的TComponent s

Attach a generic constraint to your method, to ensure that your Ts are Components

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

这篇关于类型"T"不能用作通用类型或方法中的类型参数"T"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆