Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

c# - Keyword 'this' (Me) is not available calling the base constructor

In the inherited class I use the base constructor, but I can't use the class's members calling this base constructor.

In this example I have a PicturedLabel that knows its own color and has an image. A TypedLabel : PictureLabel knows its type but uses the base color.

The (base) image that uses TypedLabel should be colored with the (base)color, however, I can't obtain this color

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

A workaround?

/// 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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This error does make a lot of sense.

If you were allowed to use this in that way there would be a timing problem. What value do you expect LabelColor to have (ie, when is it initialized)? The constructor for TypedLabel hasn't run yet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...