簡體   English   中英

類型“ 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行上,出現以下錯誤:

類型“ T”不能用作通用類型或方法“ GameObject.AddComponent()”中的類型參數“ T”。 沒有從“ T”到“ UnityEngine.Component”的裝箱轉換或類型參數轉換。

我不確定該如何解決此錯誤,為什么我不能這樣做?

問題是AddObject方法返回一個Component 您需要告訴編譯器您的T實際上是Component的一種。

將通用約束附加到您的方法,以確保TComponent

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM