关键字'this'(Me)无法调用基础构造函数

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)

Hen*_*man 5

这个错误确实很有意义.

如果您被允许以this这种方式使用,则会出现计时问题.您期望LabelColor具有什么价值(即,何时初始化)?TypedLabel的构造函数尚未运行.

  • 但是您仍然在调用基本ctor,因此在设置之前使用LabelColor. (2认同)
  • 我认为这是对编译错误的解释,这是非常明显的,但不是问题的解决方案。这是一个有效的问题,作者在这里寻求解决方法。 (2认同)
  • 解决方案非常简单,使用基础中的默认 ctor 并将图片分配到主体内。 (2认同)

Fad*_*man 1

我认为作为一种解决方法,我将按如下方式实现:

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 公开,并且每当用户更改任何这些属性时,您都可以重新创建图像并将其设置为您的基类,以便您始终可以保证在图片框中使用代表性图像