C#泛型和类型检查混淆

1 c# generics types

首先,一些课程:

public abstract class Component
{
    GenericSystem mySystem;

    public Component() { mySystem = null;}

    public void SetSystem(GenericSystem aSystem) { mySystem = aSystem; }
}

public class PhysicsComponent : Component
{
    int pos;    

    public PhysicsComponent(int x) : base() { pos = x; }
}


public abstract class GenericSystem : List<Component>
{
    public Type ComponentType;
    public GenericSystem(Type componentType)
    { ComponentType = componentType; }
    public void RegisterComponent(c)
    {
        Add(c);
        c.SetSystem(this);
    }
}

public class PhysicsSystem : GenericSystem
{
    public PhysicsSystem() : base(typeof(PhysicsComponent)) { }
}

public static GenericEngine
{
    List<GenericSystem> systems = new List<GenericSystem>();

    //... Code here that adds some GenericSystems to the systems ...

    public static void RegisterComponent(Component c)
    {
        foreach(GenericSystem aSystem in systems)
        {
            Type t = aSystem.ComponentType;
            //PROBLEM IS HERE
            t c_as_t = c as t;
            //
            if ( c_as_t != null)
                aSystem.RegisterComponent(c);
        }


    }

}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是"无法找到类型或名称空间''."

我希望每个GenericSystem人都有一个Component它想要注册的类型.这样,任何注册新的Component c简单调用GenericEngine.RegisterComponent(c)和所有对该类型组件感兴趣的系统都会注册它.

理想情况下,我希望代码更符合以下方面:

     //where T must be a child of Component
    public abstract class GenericSystem<T> : List<Component> { /... }
    public class PhysicsSystem : GenericSystem<PhysicsComponent>
Run Code Online (Sandbox Code Playgroud)

我怀疑这不是一个非常复杂的问题,而且我错过了一些关于C#如何处理类型(或者更令人尴尬的是,泛型一般)的内容,所以如果这是一个简单的问题,请指出我的阅读方向材料.提前致谢!

Eri*_*ert 9

局部变量声明和"as"不起作用."t"是一个表达式,在运行时计算为对表示类型的对象的引用.本地decl和"as"期望一个程序片段在编译时命名一个类型.

你正试着把蛋糕放在一堆蛋糕食谱书上; 虽然蛋糕和蛋糕食谱书密切相关,但它们并不是同一类.

如果要确定在运行时是否对象c是t对象描述的类型,则可以在c上调用GetType并确定这两种类型是否(1)相等,如果需要标识,或者(2) )兼容,如果您只需要一个与另一个兼容.


理想情况下,我希望代码更符合以下方面:

 //where T must be a child of Component
public abstract class GenericSystem<T> : List<Component>
Run Code Online (Sandbox Code Playgroud)

好的,然后说:

public abstract class GenericSystem<T> : List<Component> where T : Component 
Run Code Online (Sandbox Code Playgroud)

看看你的设计,其他事情似乎很可疑.通用系统实际上是一种组件列表,还是包含组件列表的东西?使用推导来表达"是一种"关系.使用包含来表达"容器"关系.汽车不是一种车轮清单; 一辆车一个轮子列表.

  • "汽车不是一种轮子列表"的+1.这可能是一个常见的陷阱,因为我最早的设计总是表现出这个问题. (2认同)