c# - 继承方案

标签 c# .net inheritance polymorphism

我一直致力于构建多个从一个基类继承的类,但现阶段我对继承和多态性在 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; } }
}

但是,大多数派生类中的非抽象变量都是相同的,但并非全部派生类都相同。

我可以使它们全部抽象并强制每个类提供它自己的值,但这似乎违反直觉。我更喜欢的是一种在基类中提供值并在需要时在派生类中提供重写的方法。

有办法做到这一点吗?我知道这可以通过声明为虚拟的方法来完成。这允许派生类使用基类方法,除非它提供了自己的方法之一。当然有类似的事情存在吗?

最佳答案

What I would prefer is a way to provide a value in the base class and provide an override in a derived class if needed.

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

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

关于c# - 继承方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009877/

相关文章:

c# - 按数字方式对 List<String[]> 进行排序

c# - DataGridViewCell 编辑模式下的 Ctrl + c 复制整行

c# - 有没有一个好的算法来检测2个矩阵是否相似

c# - iTextSharp IOException "Trailer not found"

PHP : Does extending class need another 'use' to call namespace?

c# - 如何查看路由器开放了哪些端口

c# Win Form - CLR 无法从 COM 上下文转换

.net - VB.NET 中的产量

javascript - filter() 有问题,当我扩展 Array 类时

Python 双重继承