当前位置: 首页 > 编程语言 > C#

类型’T’不能用作generics类型或方法中的类型参数’T’分享

时间:2023-04-10 21:44:34 C#

C#学习教程:Type'T'cannotbeusedasatypeparameter'T'inagenerictypeormethod以下方法:protectedTAttachComponent(){TgsComponent=gameObject.GetComponent();如果(gsComponent==null){gsComponent=gameObject.AddComponent();}返回gsComponent;在AddComponent行,我收到以下错误:类型“T”不能用作方法“GameObject.AddComponent()”中的泛型类型或类型参数“T”。没有从“T”到“UnityEngine.Component”的装箱转换或类型参数转换。我不知道我能做些什么来修复这个错误,为什么我不能这样做?问题在于AddObject方法返回一个组件。你需要告诉编译器你的T实际上是一种Component。给你的方法附加泛型约束以确保你的T对Component有用,需要了解更多C#学习教程,希望大家多多关注—protectedvoidAttachComponent()whereT:Component{//你的代码。}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: