【问题标题】:C# Class Inheretance - Possible to change a variable in subclass?C# 类继承 - 可以更改子类中的变量吗?
【发布时间】:2013-11-20 09:59:43
【问题描述】:

我正在用 C# 制作一个非常基本的游戏,并使用类图作为指导。

我有一个Building 类和一个Room 类。 在我的图表上它说Room 继承自Building,所以Building 在这种情况下是超类。

我的Building 类包含用于保存房间的设置数组

public class building // Building Object Class
{
    const int SizeConst = 4; 
    private int[,] Cells; 

    public int[,] create() 
    {
        Cells = new int[SizeConst, SizeConst]; 
        return Cells;
    }
}

Room 是完全一样的,尽管能够单独更改大小常量会很好。

例如,BuildingSize 常量可以保持为 4,提供 25 个房间。但是,如果我想将 RoomSize 常量更改为 5 以获得 36 个移动空间怎么办?

【问题讨论】:

  • 您可以将常量更改为具有硬编码值的虚拟吸气剂。你可以在那里找到如何做到这一点:stackoverflow.com/questions/770437/…
  • 太好了,谢谢你的帮助
  • 不得不说 Room 继承自建筑似乎是一个糟糕的举动。无论是拥有共同祖先,还是使用界面,都应该为您提供更好的设计。建筑物有房间,并不意味着房间就是建筑物。
  • 我明白你的意思,我对 UML 和类图还很陌生,发现它们令人难以置信的混乱。你认为它们应该完全是独立的对象吗?
  • 不能从这里说,但是继承与聚合的规则是 Is a ?一种 ?或者有一个?一种 ?。那么房间是建筑物吗?不,建筑物有房间吗?是的。什么常见的行为说服了你继承。这两个位置?如果是这样,也许 Building 和 room 应该是一个 Location,或者它们都应该实现 ILocatable

标签: c#


【解决方案1】:

您不能覆盖常量(这不会使其成为常量)。 您应该提供一个虚拟 getter 或方法:

    public class building // Building Object Class
    {
        protected virtual int Size{ get;}
        private int[,] Cells; 

        public int[,] create() 
        {
            Cells = new int[Size, Size]; 
            return Cells;
         }
    }

    public class Room
    {
        protected virtual int Size
        {
             get
             {
                 // return custom value here
             }
        }
    }

【讨论】:

    【解决方案2】:

    基本上你不能改变 constant,但我建议你使用多态性并创建将返回所需值的虚拟属性或方法。

    例如:

    public class Building
    {
        public virtual int CellCount { get { return 5; } }
    }
    
    public class Room : Building
    {
        public override int CellCount { get { return 6; } }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2013-04-19
      • 2015-12-09
      • 1970-01-01
      • 2019-07-10
      • 2011-04-04
      • 2019-03-28
      相关资源
      最近更新 更多