繁体   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