【发布时间】:2011-01-27 15:11:54
【问题描述】:
在继承的类中,我使用基构造函数,但不能使用类的成员调用此基构造函数。
在此示例中,我有一个 PicturedLabel,它知道自己的颜色并具有图像。 TypedLabel : PictureLabel 知道它的类型,但使用基色。
使用TypedLabel的(基础)图像应该用(基础)颜色着色,但是我无法获得这种颜色
错误:关键字“this”在当前上下文中不可用`
解决方法?
/// 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 有趣的问题和很好的有效例子