ser*_*hio 4 .net c# vb.net oop
在继承的类中,我使用基础构造函数,但我不能使用类的成员调用此基础构造函数.
在这个例子中,我有一张PicturedLabel,它知道自己的颜色并有一个图像.A 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个错误确实很有意义.
如果您被允许以this这种方式使用,则会出现计时问题.您期望LabelColor具有什么价值(即,何时初始化)?TypedLabel的构造函数尚未运行.
我认为作为一种解决方法,我将按如下方式实现:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我在此上下文中将 Type 属性设置为私有,但它也可以是公共的。事实上,您可以将 Type 和 LabelColour 公开,并且每当用户更改任何这些属性时,您都可以重新创建图像并将其设置为您的基类,以便您始终可以保证在图片框中使用代表性图像