在繼承的類中,我使用基礎構造函數,但不能使用調用此基礎構造函數的類的成員。關鍵字'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;
}
}
+1有趣的問題和很好的有效的例子 – 2010-03-15 10:41:25