2
我一直在努力构建几个从一个基类继承的类,但我并不完全相信在这个阶段继承和多态在C#中的工作方式。继承解决方案
我的基类,看起来是这样的:
abstract class Structure
{
public int currentCost = 0;
public int currentArea = 0;
public int currentPopulation = 0;
public int currentConstruction = 0;
public int currentEnergy = 0;
public int currentEconomy = 0;
public abstract int baseCost { get; }
public abstract int baseEnergy { get; }
public abstract int baseEconomy { get; }
public abstract int baseConstruction { get; }
public int baseArea = -1;
public int basePopulation = -1;
public int level = 0;
public abstract string structureName { get; }
}
现在,从Structure
类继承的类将作出的抽象变量这是很好的提供了自己的任务,因为大多数的类大相径庭的他们分配的数字。 抽象变量在派生类使用在下面的(不完全的)的方式:
class BiosphereModification : Structure
{
const int baseEconomyBiosphereModification = 0;
const int baseConstructionBiosphereModification = 0;
const int baseCostBiosphereModification = 2000;
const int baseEnergyBiosphereModification = 0;
const int baseFertilityBiosphereModification = 1;
const string structureNameBiosphereModification = "BiosphereModification";
public override int baseCost { get { return baseCostBiosphereModification; } }
public override int baseEconomy { get { return baseEconomyBiosphereModification; } }
public override int baseEnergy { get { return baseEnergyBiosphereModification; } }
public override int baseConstruction { get { return baseConstructionBiosphereModification; } }
}
然而,非抽象变量将跨越大部分派生类的相同,但不是所有的人。
我可以让他们全部抽象并强迫每个班级提供它自己的价值,但这似乎违反直觉。我更喜欢的是在基类中提供值并在需要时在派生类中提供重写的方法。
有没有办法做到这一点?我知道这可以通过声明为virtual
的方法来完成。这允许派生类使用基类方法,除非它提供了它自己的一个。当然有类似的东西存在吗?
这似乎做我想做的,谢谢。对于不需要派生类更改但必要的字段,只需使用常规字段而不是属性? – Arcadian 2012-08-17 17:33:44
@Arcadian我建议不要使用公共字段 - 真的没有理由不使用公共API中的任何属性,因为它对将来的版本控制更安全。 – 2012-08-17 17:35:01
是的,我意识到这一点。我刚刚做了一个匆忙的例子,我正在做什么。我为我的领域使用'protected'或'private'。但感谢提醒。 – Arcadian 2012-08-17 17:40:54