c# - 类型 'T' 不能用作泛型类型或方法中的类型参数 'T'

标签 c# unity3d

我有以下方法:

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

AddComponent 行我收到以下错误:

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'.

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

最佳答案

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

将通用约束附加到您的方法,以确保您的 TComponent

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

关于c# - 类型 'T' 不能用作泛型类型或方法中的类型参数 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137551/

相关文章:

c# - 通过脚本在变量中存储对预制件的引用(不是由编辑器/检查员)

c# - 在 Unity 中保存/加载数据

c# - 从达到的最后一关继续游戏

c# - 从网络驱动器连接/复制

c# - 使用参数查询 MySQL & C#

c# - 为什么找不到方法 app.UseSwaggerUI(...)?

c# - 在 cshtml View 中导入 c# 类

c# - VS2015自动完成功能不起作用

c# - 将十六进制字符串转换回字符

c# - 无法在带有输入字段 Unity 的 Scroll rect 中滚动