简体   繁体   English

在泛型方法中使用类型静态方法。 C#

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

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

In Component< T > GetMask() decleared as static. 在Component <T>中,GetMask()被清除为静态。 So why I can't execute this method, compiler even doesn't see any methods, if I use restriction that guarantee at compile time that nothing else then Component< T > and inherited types will't use as T? 那么,为什么我不能执行该方法,如果我使用限制来保证在编译时不能再使Component <T>和继承的类型不用作T,为什么编译器甚至看不到任何方法?

I know the way how to implement it through instantiating T type object, but this implementation not suitable for my task. 我知道如何通过实例化T类型对象来实现它的方式,但是这种实现方式不适合我的任务。

To make question have an alternative answers, I need get component of base class Component< T > from wich user inherits, from entity in wich all components stores in Dictionary< TypeMask, ComponentBase >. 为了使问题有其他答案,我需要从用户继承的基类Component <T>的组件中获取所有来自Dictionary <TypeMask,ComponentBase>的实体。 Component< T > inherits from ComponentBase. Component <T>继承自ComponentBase。 To get component from entity there are GetComponent() methods. 要从实体获取组件,可以使用GetComponent()方法。 If don't use generics methods user will have write the same as written at 4-th line of example below. 如果不使用泛型方法,则用户将编写与以下示例的第4行相同的内容。 So, maybe there is alternative way to get components, but i don't see it. 因此,也许有获取组件的替代方法,但我没有看到它。

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

I'm sorry for grammatical mistakes. 对不起语法错误。

You can access the static method over Component instead of T 您可以通过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