簡體   English   中英

在泛型方法中使用類型靜態方法。 C#

[英]Using type static methods in generic method. C#

public T GetComponent<T>() where T : Component<T>
{
    return (T) components[T.GetMask()];
}

在Component <T>中,GetMask()被清除為靜態。 那么,為什么我不能執行該方法,如果我使用限制來保證在編譯時不能再使Component <T>和繼承的類型不用作T,為什么編譯器甚至看不到任何方法?

我知道如何通過實例化T類型對象來實現它的方式,但是這種實現方式不適合我的任務。

為了使問題有其他答案,我需要從用戶繼承的基類Component <T>的組件中獲取所有來自Dictionary <TypeMask,ComponentBase>的實體。 Component <T>繼承自ComponentBase。 要從實體獲取組件,可以使用GetComponent()方法。 如果不使用泛型方法,則用戶將編寫與以下示例的第4行相同的內容。 因此,也許有獲取組件的替代方法,但我沒有看到它。

Position pos = entity.GetComponent(Position.Mask); //I need that
Position pos = entity.GetComponent<Position>(); //or that

Position pos = (Position)entity.GetComponent(Position.Mask); //but not that

對不起語法錯誤。

您可以通過Component而不是T訪問靜態方法

public T GetComponent<T>() where T : Component<T> {
    return (T) components[Component<T>.GetMask()];
}

暫無
暫無

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

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