【发布时间】:2011-11-04 21:13:06
【问题描述】:
首先,一些课程:
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);
}
}
}
我得到的错误是“找不到类型或命名空间't'。”
我希望每个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>
我怀疑这不是一个非常复杂的问题,而且我遗漏了一些关于 C# 如何处理类型(或者,更尴尬的是,一般来说是泛型)的内容,所以如果这是一个简单的问题,请指出我的方向的一些阅读材料。提前致谢!
【问题讨论】:
-
您可以使用泛型约束来解决“其中 T 必须是 Component 的子级”问题。这真的很简单 -
where T : Component。这种类型的注册+通知听起来像the Observer Design Pattern,所以你可能想看看。我想你会想要做两层这种模式。