2012-11-03 29 views
0

我有一個基類:傳承 - 基於孩子值在初始化時變變

class Tile{} 

而其他幾個延伸瓷磚

class Free : Tile{} 
class Wall : Tile{} 

每個瓷磚有它自己的紋理,它不是字符串,但它的Texture2D必須在初始化時加載。我想代碼將類似於這一點,但我不知道如何正確地創建此:

class Tile{ 
    static Texture2D texture; //Static will use less ram because it will be same for inherited class? 
    static string texture_path; //This is set by inherited class 
    public Tile(){ 
     if(texture==null) 
      texture = LoadTexture(texture_path); 
    } 
} 

class Free : Tile{ 
    static string texture_path = "Content/wall.png"; 
} 

隨着換言之,所有的免費瓷磚具有相同的紋理和所有牆磚具有相同的紋理 - 這就是爲什麼在我意見我應該使用靜態。

如何正確執行此操作?

+1

什麼是你的問題?問題通常有一個問號。 –

回答

0

你需要做的是在基類中聲明屬性併爲子類提供一個選項來覆蓋它。如果您願意,這可以讓您提供默認值。

有些事情是這樣的:

public class Tile 
{ 
    private string _texturePath = String.Empty; 
    private Texture2D _texture; 
    protected virtual string TexturePath { private get { return _texturePath; } set { _texturePath = value; } } 

    public Tile() 
    { 
     if (!string.IsNullOrWhiteSpace(TexturePath)) 
      _texture = LoadTexture(TexturePath); 
    } 
    private Texture2D LoadTexture(string texturePath) 
    { 
     throw new NotImplementedException(); 
    } 
} 

internal class Texture2D 
{ 
} 

public sealed class Free:Tile 
{ 
    protected override string TexturePath 
    { 
     set 
     { 
      if (value == null) throw new ArgumentNullException("value"); 
      base.TexturePath = "Content/wall.png"; 
     } 
    } 
} 

如果你不想提供一個默認的紋理路徑,你可以計劃,使財產和基類的抽象。

+0

Texture2D會爲每個新初始化的Free:tile加載嗎? – ewooycom

+0

是的,在這種情況下。如果你想讓空閒類加載一次紋理,並且所有Free對象共享該紋理實例,則必須通過允許紋理2d屬性移動到子類並提供返回紋理的singelton的工廠來輕微更改該實現基於Tile實現請求的對象 –

0

如果你希望你的基類有權訪問texture_path,你應該在你的基類中聲明它。

基類不知道任何關於在其子類中聲明的字段,屬性或方法。這是由BTW設計的...

0

根據你的問題,你希望Free的所有實例共享一個紋理和Wall的所有實例以共享紋理。這意味着您希望static字段texturetexture_path位於子類中,而不是父類。

例:

public class Tile { } 

public class Free : Tile 
{ 
    private static Texture2D texture; 
    private static string texture_path; 
} 

public class Wall : Tile 
{ 
    private static Texture2D texture; 
    private static string texture_path; 
} 

如果你想Tile引用有texturetexture_path性能,讓您可以從一個實例訪問共享texturetexture_path,你需要一個virtualabstract財產。

例:

public abstract class Tile 
{ 
    public abstract Texture2D Texture { get; } 
    public abstract string TexturePath { get; } 
} 

public class Free : Tile 
{ 
    private static Texture2D texture; 
    private static string texture_path; 

    public override Texture2D Texture { get { return texture; } } 
    public override string TexturePath { get { return texture_path; } } 
} 

// and similarly for Wall