2012-04-22 20 views
0

我在C#這樣的類:Overiding不斷

public class Foo 
{ 
    public static readonly int SIZE = 2; 
    private int[] array; 

    public Foo 
    { 
     array = new int[SIZE]; 
    } 

} 

Bar類:

public class Bar : Foo 
{ 
    public static readonly int SIZE = 4; 

} 

我想accopmlish是創建數組的大小一欄實例從overrided SIZE取值。如何正確地做到這一點?

+0

您可以在構造函數中設置只讀參數,但可能不是靜態只讀,因爲它需要在不帶參數的靜態構造函數中設置。 – kenny 2012-04-22 11:04:40

回答

3

你不能這樣做。你可以使用一個虛擬的方法:

public class Foo 
{ 
    protected virtual int GetSize(){return 2;}; 
    private int[] array; 

    public Foo 
    { 
     array = new int[GetSize()]; 
    } 
} 

它也可以使用反射來尋找一個靜態字段SIZE,但我不建議。

2

您的SIZE常量是靜態的,並且靜態字段不會被繼承 - Foo.SIZE和Bar.SIZE是兩個不同的常量,它們之間沒有任何關係。這就是爲什麼Foo的構造函數的調用將始終以2初始化,不是4

你可以做的就是創建Foo中protected virtual void Initialize()方法初始化與陣列2,並覆蓋它在酒吧與4

0
初始化

你不能繼承靜態字段;改爲使用以下內容:

public class Foo 
{ 
    protected virtual int SIZE 
    { 
     get 
     { 
      return 2; 
     } 
    } 

    private int[] array; 

    public Foo() 
    { 
     array = new int[SIZE]; 
    } 
} 

public class Bar : Foo 
{ 
    protected override int SIZE 
    { 
     get 
     { 
      return 4; 
     } 
    } 
} 

虛擬就像是在說「這是基類的默認值」;而Override改變實現「Foo」的類的值。

+1

-1您不能在字段上放置虛擬和覆蓋。而是使用屬性或方法來返回值。 – base2 2012-04-22 11:07:19

+0

公平警察,改爲使用屬性 – 2012-04-22 11:10:52