Kac*_*acy 2 c# polymorphism inheritance
我有一个名为 Projectile 的基类和一个名为 SaiBlast 的子类。在我的 SaiBlast 类中,我想使用从 Projectile 继承的方法,但在这些继承的方法中仍然使用属于 SaiBlast 的 const 变量。
这是一个最小的例子。
基类:
class Projectile
{
protected const float defaultSpeed = 50;
public void Shoot( float speed = defaultSpeed ) //optional parameter
{
//code
}
}
Run Code Online (Sandbox Code Playgroud)
儿童班:
class SaiBlast : Projectile
{
protected new const float defaultSpeed = 100;
}
Run Code Online (Sandbox Code Playgroud)
现在如果我说:
SaiBlast saiBlast = new SaiBlast();
saiBlast.Shoot();
Run Code Online (Sandbox Code Playgroud)
Shoot() 应使用值 100,因为这是 sai 爆炸的默认速度。现在它通常使用 Projectiles 的默认速度,即 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; } }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |