【发布时间】:2013-12-15 17:33:30
【问题描述】:
我有一个基类“Powerup”,然后是该类“Bomb”、“Repel”和“Wall”的 3 个子类。
在基类中,我想获取派生类类型,以便可以将其作为方法参数传递。
现在我使用如下代码解决了这个问题:
if (this is BombPowerup)
AddComponent<BombPowerup>();
else if (this is RepelPowerup)
AddComponent<RepelPowerup>();
else if (this is WallPowerup)
AddComponent<WallPowerup>();
但它并不是真正可扩展的。我知道我可以创建一个抽象方法并让子类自己完成每一行,但我想知道我可以在基类中使用的解决方案以进行良好的学习。
谢谢。
编辑: AddComponent方法定义如下
void AddComponent<T>() where T : Powerup
【问题讨论】:
-
贴出
AddComponent方法的定义。另外,应该为每个后代类调用AddComponent,还是应该省略一些后代? -
每个后代班级。 AddComponent 只是一个具有泛型类型的方法,其中类型继承自 Powerup
标签: c# inheritance