gpt4 book ai didi

c# - C#中的变量对象

转载 作者:行者123 更新时间:2023-11-30 13:09:56 25 4
gpt4 key购买 nike

我有一个名为 gameObject 的类,它的一个属性位于 component 中,属于 object 类型:

public object component;

并且我正在尝试使用此对象 充当一个对象,该对象可以容纳您为其提供的任何类的对象。例如

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

这可以吗?我该怎么做?

最佳答案

typeof(unit)也是一个对象,它不同于component。您应该改为执行 component.GetType():

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

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

if(test.component is unit)

不过,这仍然不允许您在没有转换的情况下调用 Draw。同时检查和转换的最简单方法如下:

unit u = test.component as unit;
if (u != null) {
u.Draw();
}

关于c# - C#中的变量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12213089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com