我有这样的东西:
class powerup {
public static int cooldown = 1;
}
class freeze : powerup {
//some unrelated code
}
class burn : powerup {
//unrelated
}
并且我想为冻结和燃烧加电的冷却时间设置不同的值,并且采用静态方式,因为我无法在设置冷却时间的地方实例化它们,并且让它们更有意义静态的,因为它们是唯一的。所以我觉得我需要用“ new”覆盖冷却时间,但是感觉不对。有什么我不知道的解决方案吗? 预先感谢
答案 0 :(得分:3)
C#中没有覆盖性和静态性的结合;在某种意义上是相反的。
更好的技术是制作实例;如果可行,这些实例可以是单例。我倾向于做这样的事情:
libMyExternal.so
但是当这些都是单例时,我特别喜欢的技术是:
abstract class Powerup
{
public virtual int Cooldown => 1
}
sealed class Freeze : Powerup
{
}
sealed class Burn : Powerup
{
public override int Cooldown => 2;
}
现在查看使用站点:
abstract class Powerup
{
private Powerup() {} // Prevent instantiation
public virtual int Cooldown => 1
public static readonly Powerup Freeze = new FreezePower();
private sealed class FreezePower : Powerup
{
}
public static readonly Powerup Burn = new BurnPower();
private sealed class BurnPower : Powerup
{
public override int Cooldown => 2;
}
}
在我认为的使用站点上,这看起来真的很棒。
答案 1 :(得分:2)
您可以使用new modifier隐藏子类的父属性,例如:
class powerup
{
public static int cooldown = 1;
}
class freeze : powerup
{
public new static int cooldown = 3;
//some unrelated code
}
class burn : powerup
{
public new static int cooldown = 2;
//unrelated
}
这提供了以下结果:
Console.WriteLine($"powerup: {powerup.cooldown}");
Console.WriteLine($"freeze: {freeze.cooldown}");
Console.WriteLine($"burn: {burn.cooldown}");
答案 2 :(得分:0)
我相信您想更新特定通电的所有实例的冷却时间值。在这种情况下,我将使用以下内容:
interface IPowerup {
int Cooldown { get; set; }
}
class Freeze : IPowerup {
private static int _cooldown;
public int Cooldown { get { return _cooldown } set { _cooldown = value; }
public Freeze() { Cooldown = 1; }
}
class Burn : IPowerup {
private static int _cooldown;
public int Cooldown { get { return _cooldown } set { _cooldown = value; }
public Burn() { Cooldown = 2; }
}
因此,现在,如果您为一次加电设置冷却时间,则为所有加电设置值。
您还可以取消构造函数,实例化加电并按如下方式设置冷却时间:
var burnPowerup = new Burn { Cooldown = 2 };