3

我有一个名为 gameObject 的类,它的一个属性被调用component并且是类型object

public object component;

我正试图用它object作为一个对象,它可以保存你给它的任何类的对象。例如

unit c = new unit(...)
gameObject test = new gameObject(...)
test.component = c;

我想通过组件对象使用c对象。例如

if(test.component==typeof(unit))
    test.component.Draw();//draw is a function of the unit object

这可能吗?我该怎么做?

4

6 回答 6

7

typeof(unit)也是一个对象,它不同于component. 你应该这样做component.GetType()

if(test.component.GetType()==typeof(unit))

这不会检查派生类型,但会:

if(test.component is unit)

尽管如此,这并不能让你在Draw没有强制转换的情况下调用。最简单的同时check和cast的方法如下:

unit u = test.component as unit;
if (u != null) {
    u.Draw();
}
于 2012-08-31T10:04:12.120 回答
5

是的,这叫做铸造。像这样:

if(test.component is unit)
  ((unit)test.component).Draw();
于 2012-08-31T10:02:29.183 回答
5

使用接口并使单元类实现该接口。在接口中定义 Draw() 方法,并将组件声明为您定义的接口的类型。

public interface IDrawable
{
 void Draw();
}

public IDrawable component;

public class unit : IDrawable
...
于 2012-08-31T10:03:37.200 回答
3

if (test.component is unit) ((unit)(test.component)).Draw();

于 2012-08-31T10:02:57.243 回答
1

正如其他人所说-您可以将所有内容都投射到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();
        }
    }
}
于 2012-08-31T10:10:01.647 回答
0

要使用对象的特定行为,您必须将其转换为特定类型。使用变量引用它,object您只能将其用作object实例。

于 2012-08-31T10:05:02.317 回答