2010-03-15 81 views
4

在繼承的類中,我使用基礎構造函數,但不能使用調用此基礎構造函數的類的成員。關鍵字'this'(Me)不可用調用基礎構造函數

在這個例子中,我有一個PicturedLabel知道它自己的顏色,並有一個圖像。 A TypedLabel : PictureLabel知道它的類型,但使用基本顏色。

使用TypedLabel應與(基極)的顏色來着色的(鹼)圖像,但是,我不能得到這種顏色

Error: Keyword 'this' is not available in the current context`

一種解決方法?

/// base class 
public class PicturedLabel : Label 
{ 
    PictureBox pb = new PictureBox(); 
    public Color LabelColor; 

    public PicturedLabel() 
    { 
     // initialised here in a specific way 
     LabelColor = Color.Red; 
    } 

    public PicturedLabel(Image img) 
     : base() 
    { 
     pb.Image = img; 
     this.Controls.Add(pb); 
    } 
} 

public enum LabelType { A, B } 

/// derived class 
public class TypedLabel : PicturedLabel 
{ 
    public TypedLabel(LabelType type) 
     : base(GetImageFromType(type, this.LabelColor)) 
    //Error: Keyword 'this' is not available in the current context 
    { 
    } 

    public static Image GetImageFromType(LabelType type, Color c) 
    { 
     Image result = new Bitmap(10, 10); 
     Rectangle rec = new Rectangle(0, 0, 10, 10); 
     Pen pen = new Pen(c); 
     Graphics g = Graphics.FromImage(result); 
     switch (type) { 
      case LabelType.A: g.DrawRectangle(pen, rec); break; 
      case LabelType.B: g.DrawEllipse(pen, rec); break; 
     } 
     return result; 
    } 
} 
+0

+1有趣的問題和很好的有效的例子 – 2010-03-15 10:41:25

回答

1

我覺得作爲一個解決方法,我將在下面爲實現這個你已經不叫基類的構造尚未:this.LabelColor調用基類成員不可用

public class PicturedLabel : Label 
{ 
    protected Image 
    { 
     get {...} 
     set {...} 
    } 
    ............ 
} 

public class TypedLabel : PicturedLabel 
{ 
    public TypedLabel(LabelType type) 
     :base(...) 
    { 
     Type = type; 
    } 
    private LabelType Type 
    { 
     set 
     { 
     Image = GetImageFromType(value, LabelColor); 
     } 
    } 
} 

編輯:我使Type屬性專用於此上下文,但它也可以是公共的。實際上,您可以將Type和LabelColour公開,並且每當用戶更改任何這些屬性時,您都可以重新創建圖像並將其設置爲基類,以便始終可以保證在圖片框中使用代表性圖像。

5

這個錯誤的確有很大的意義。

如果您被允許以這種方式使用this將會出現計時問題。你期望LabelColor有什麼價值(即什麼時候初始化)? TypedLabel的構造函數尚未運行。

+0

,你可以在基類中看到,我在無參數的構造函數中初始化它。最後,假設我默認聲明'public Color LabelColor = Color.Red;' – serhio 2010-03-15 10:41:43

+2

但是您仍然在調用該基本ctor的過程中,因此您在使用LabelColor之前設置它。 – 2010-03-15 10:44:24

+0

並用初始化器聲明它可以解決這個問題,但是這不會使這個''''安全使用。 – 2010-03-15 10:45:55

0

屬性LabelColor目前未初始化,因此它將爲空。事實上,「這個」在那個時候沒有被初始化,因爲在創建「this」之前調用基礎構造函數,這就是爲什麼不能調用「this」的原因。

+0

我明白了。但尋找解決方案。 – serhio 2010-03-15 10:44:01

+0

也許把LabelColor作爲構造函數的參數? – 2010-03-15 10:50:17

+0

也許是一個好方法,但不適合我的情況。基類定義自己的顏色。 – serhio 2010-03-15 11:21:13

2

您正試圖訪問尚未初始化的成員。當你寫: base(...)

public TypedLabel(LabelType type) 
     : base() 
    { 
     pb.Image = GetImageFromType(type, this.LabelColor); 
    } 
+0

是的......是的......但是。顏色位於基類中,但該過程位於派生類中。 – serhio 2010-03-15 10:47:19

+1

您必須對圖片框進行保護或提供受保護的屬性以訪問派生類中的圖像。 – Seb 2010-03-15 10:48:25