【问题标题】:Inheritance solution继承解决方案
【发布时间】:2012-08-14 03:26:21
【问题描述】:

我一直致力于构建几个从一个基类继承的类,但我对现阶段 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 的方法来完成。这允许派生类使用基类方法,除非它提供它自己的方法之一。肯定存在类似的事情吗?

【问题讨论】:

    标签: c# .net inheritance polymorphism


    【解决方案1】:

    我更喜欢一种在基类中提供值并在需要时在派生类中提供覆盖的方法。

    属性也可以声明为虚拟的:

    public virtual int BaseCost { get { return 0; } }
    public virtual int BaseEnergy { get { return 42; } }
    public virtual int BaseEconomy { get { return 3982; } }
    public virtual int BaseConstruction { get { return 398829; } }
    

    然后您可以在适当的时候覆盖它们:

    public override int BaseCost { get { return 2; } }
    

    【讨论】:

    • 这似乎符合我的要求,谢谢。对于不需要被派生类改变但又是必要的字段,你就用普通字段代替属性?
    • @Arcadian 我建议永远不要使用公共字段 - 确实没有理由不在公共 API 中的任何地方使用属性,因为它对未来的版本控制更安全。
    • 是的,我意识到这一点。我只是草率地举了一个例子来说明我在做什么。我的字段使用protectedprivate。不过谢谢你的提醒。
    猜你喜欢
    • 2012-11-15
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多