我有一个名为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 blast的默认速度。现在,它对射弹的默认速度通常为50。
我曾一半希望它能工作,因为多态性,但我认为我会遇到这个问题,因为编译器会在编译时为常量填充硬值。

我该怎么做?

最佳答案

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; } }
}

09-17 19:45