我有一个名为Projectile的基类和一个名为SaiBlast的子类。在我的SaiBlast类中,我想使用从Projectile继承的方法,但仍然在这些继承的方法中使用属于SaiBlast的const变量。
这是一个最小的例子。
基类:
class Projectile
{
protected const float defaultSpeed = 50;
public void Shoot( float speed = defaultSpeed ) //optional parameter
{
//code
}
}
儿童班:
class SaiBlast : Projectile
{
protected new const float defaultSpeed = 100;
}
现在,如果我说:
SaiBlast saiBlast = new SaiBlast();
saiBlast.Shoot();
Shoot()应该使用值100,因为这是sai blasts的默认速度。现在它使用普通弹丸的默认速度为50。 由于多态性,我有一半期待这个工作,但我想我会遇到这个问题因为编译器在编译时填充了常量的硬值。
我该如何做到这一点?
答案 0 :(得分:4)
class Projectile
{
protected virtual float DefaultSpeed { get { return 50; } }
public void Shoot(float? speed = null)
{
float actualSpeed = speed ?? DefaultSpeed;
//Do stuff
}
}
class SaiBlast : Projectile
{
protected override float DefaultSpeed { get { return 100; } }
}