c#中的变量对象

use*_*136 3 c# variables typeof object

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

public object component;
Run Code Online (Sandbox Code Playgroud)

而我正在尝试使用它object作为一个对象,可以保存你给它的任何类的对象.例如

unit c = new unit(...)
gameObject test = new gameObject(...)
test.component = c;
Run Code Online (Sandbox Code Playgroud)

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

if(test.component==typeof(unit))
    test.component.Draw();//draw is a function of the unit object
Run Code Online (Sandbox Code Playgroud)

这可能吗?我该怎么办?

das*_*ght 7

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

if(test.component.GetType()==typeof(unit))
Run Code Online (Sandbox Code Playgroud)

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

if(test.component is unit)
Run Code Online (Sandbox Code Playgroud)

不过,这不会让你在Draw没有施法的情况下打电话.同时检查和投射的最简单方法如下:

unit u = test.component as unit;
if (u != null) {
    u.Draw();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

是的,它被称为铸造.像这样:

if(test.component is unit)
  ((unit)test.component).Draw();
Run Code Online (Sandbox Code Playgroud)


fla*_*ayn 5

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

public interface IDrawable
{
 void Draw();
}

public IDrawable component;

public class unit : IDrawable
...
Run Code Online (Sandbox Code Playgroud)