正如其他人所说-您可以将所有内容都投射到Object
. 但是你应该使用接口的一些基类来确保没有人会发送给你Int32
或其他一些意想不到的类型。但是如果所有支持的类型都有一些通用的方法,那么最好把它放在接口中。所以你可以Draw()
在没有铸造的情况下做任何事情,甚至不知道它到底是什么。
具有空接口的变体只是强制执行正确的类型:
interface IComponent
{
}
class unit : IComponent
{
//...
}
class enemy : IComponent
{
//...
}
class gameObject
{
IComponent component;//now only objects inheriting IComponent can be assigned here
public void DrawComponent()
{
unit u = component as unit;
if (u != null) {
u.Draw();
}
enemy e = component as enemy;
if (e != null) {
e.DrawIfVisible();
}
}
}
具有声明通用功能的接口的变体:
interface IDrawable
{
void Draw();
}
class unit : IDrawable
{
public void Draw(){;}
//...
}
class enemy : IDrawable
{
public void Draw(){;}
//...
}
class gameObject
{
IDrawable component;
public void DrawComponent()
{
//now you don't need to care what type component really is
//it has to be IDrawable to be assigned to test
//and because it is IDrawable, it has to have Draw() method
if (component != null) {
component.Draw();
}
}
}