2010-03-15 82 views
4

在继承的类中,我使用基础构造函数,但不能使用调用此基础构造函数的类的成员。关键字'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; 
    } 
} 
+0

+1有趣的问题和很好的有效的例子 – 2010-03-15 10:41:25

回答

1

我觉得作为一个解决方法,我将在下面为实现这个你已经不叫基类的构造尚未:this.LabelColor调用基类成员不可用

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); 
     } 
    } 
} 

编辑:我使Type属性专用于此上下文,但它也可以是公共的。实际上,您可以将Type和LabelColour公开,并且每当用户更改任何这些属性时,您都可以重新创建图像并将其设置为基类,以便始终可以保证在图片框中使用代表性图像。

5

这个错误的确有很大的意义。

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

+0

,你可以在基类中看到,我在无参数的构造函数中初始化它。最后,假设我默认声明'public Color LabelColor = Color.Red;' – serhio 2010-03-15 10:41:43

+2

但是您仍然在调用该基本ctor的过程中,因此您在使用LabelColor之前设置它。 – 2010-03-15 10:44:24

+0

并用初始化器声明它可以解决这个问题,但是这不会使这个''''安全使用。 – 2010-03-15 10:45:55

0

属性LabelColor目前未初始化,因此它将为空。事实上,“这个”在那个时候没有被初始化,因为在创建“this”之前调用基础构造函数,这就是为什么不能调用“this”的原因。

+0

我明白了。但寻找解决方案。 – serhio 2010-03-15 10:44:01

+0

也许把LabelColor作为构造函数的参数? – 2010-03-15 10:50:17

+0

也许是一个好方法,但不适合我的情况。基类定义自己的颜色。 – serhio 2010-03-15 11:21:13

2

您正试图访问尚未初始化的成员。当你写: base(...)

public TypedLabel(LabelType type) 
     : base() 
    { 
     pb.Image = GetImageFromType(type, this.LabelColor); 
    } 
+0

是的......是的......但是。颜色位于基类中,但该过程位于派生类中。 – serhio 2010-03-15 10:47:19

+1

您必须对图片框进行保护或提供受保护的属性以访问派生类中的图像。 – Seb 2010-03-15 10:48:25