[英]Get class type of derived class in base class and pass it as a type parameter
[英]Getting Child type in base class to pass as type parameter to another method
我有一个名为Powerup
的基类和2个后代类Bomb
和Repel
。
我有一个方法需要调用,我将对象类型作为参数传递。
public void PowerupExpired<T>() where T : Powerup {
//do stuff here
}
有没有办法从基类Powerup
我可以得到子类类型并将其传递给方法? 我不能使用通用类型。 传递给方法的类型必须是Powerup
类型
现在,我正在Powerup
类中使用:
if (this is BombPowerup)
PowerupManager.PowerupExpired<BombPowerup>();
else if (this is RepelPowerup)
PowerupManager.PowerupExpired<RepelPowerup>();
//etc etc
虽然这不是整洁或可扩展的。
编辑:
我忘了添加。 我不能有通用类型的原因是因为我现在要使用统一GetComponent<T>()
方法,使用参数类型在穿过PowerupExpired
,其不接受一般类型。
你是说像下面这样的东西? 我真的不明白你想要什么,但我试了一下。
使Powerup成为一个抽象类,只是所有其他powerup的基类。
public abstract class Powerup
{
// common behaviour for all powerups
}
然后每种类型的powerup都将从这个基类继承。
public class BombPowerup : Powerup
{
// specific behaviour
}
声明PowerupExpired方法,使其获取参数。
public void PowerupExpired<T>(T param) where T : Powerup
{
// for example print a type of an argument
Console.WriteLine(param.GetType().Name);
}
试用。
PowerupExpired(new BombPowerup());
在您的代码中,它看起来非常像您想要在PowerupExpired
执行不同的操作, PowerupExpired
取决于它是炸弹还是击退。 那为什么不用两种方法呢?
如果您使用泛型方法的唯一原因是使用泛型统一方法,请不要使用泛型统一方法。
有一个替代方法GetComponent(Type t)
,你传入类型(它实际上更健壮,你可以,例如,传入接口而不是从组件继承的类)。
你的代码看起来像(像):
public void PowerupExpired(PowerUp p)
{
PowerUp powerUpComponent = GetComponent(p.GetType());
}
哪里
class BombPowerup : Powerup
{}
和
class RepelPowerup : Powerup
{}
并且可能是
class Powerup : Component
{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.