2013-11-20 51 views
0

我在C#中製作了一個非常基礎的遊戲,並使用類圖作爲指導。C#類Inheretance - 可以更改子類中的變量?

我有一個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是完全一樣的,雖然這將是很好能夠改變大小不變indipendantly。

例如,SizeBuilding的常數可能會保持在4給25個房間。但是如果我想將RoomSize常數更改爲5以獲得36個移動空間呢?

+1

您可以將常量更改爲具有硬編碼值的虛擬getter。你可以找到如何做那裏:http://stackoverflow.com/questions/770437/overriding-constants-in-derived-classes-in-c-sharp – vmeln

+0

多數民衆贊成,很好,謝謝你的幫助 – Harvey

+1

不得不說,房間繼承建築似乎是一個壞的舉動。兩者都有一個共同的祖先,或使用一個接口,應該給你一個更好的設計。建築物有房間,並不意味着房間是建築物。 –

回答

0

你不能重寫一個常量(這不會使它成爲一個常量)。 你應該提供一個虛擬的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 
      } 
     } 
    } 
0

基本上你不能改變不斷,但不是這個,我建議你使用多態性與創建虛擬屬性或方法,將返回所需的值。

例如:

public class Building 
{ 
    public virtual int CellCount { get { return 5; } } 
} 

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

希望這有助於。