如何隐藏继承的属性



我正在尝试从我无法访问的另一个类中继承的类。

public class MyLabel : Label
{
    public MyLabel()
    {
        base.Text = "This text is fixed";
        base.BackgroundColor = Color.Green;
    }
}

当这样调用时,TextVisible属性仍然可用:

MyLabel lbl = new MyLabel();
lbl.Text = "Nope.";
lbl.BackgroundColor = Color.Red;

有没有办法使这两个最后两个语句无效?

您可以使用新关键字隐藏继承的属性,然后重新定义它们为ReadOnly。

public class MyLabel : Label
{
    new public string Text { get { return base.Text; } }
    new public string BackColor { get { return base.BackColor; } }
    public MyLabel()
    {
        base.Text = "This text is fixed";
        base.BackColor= Color.Green;
    }
}

继承是继承。如果您的父母通过了蓝眼睛的特征,那么特质就在您的遗传密码中。不过,这并不意味着您有蓝眼睛。继承特征时,您可能会有棕色的眼睛(主要特征(,因此您可以表达这种特征。

代码的工作原理类似。如果foobar继承,则每个foo都具有bar的特征。但是,您可以做的是覆盖具有班级特征的特征的特征。

  public override string Text
  {
            get { return "Nope"; }    
            set { return; /*or throw an exception or whatever you want to do*/ }
  }

现在,我已经向您展示了如何,如果您可以避免它,请不要做。如果您担心像Label这样的复杂对象,并且不想揭示其继承的内容,那么您的问题可能与属性上的修饰符无关,与范围修改器有关在您的实际实例上。您最好在更狭窄的范围内使用该对象,然后在其他任何东西访问它之前让其脱离范围。

您要避免这种情况的原因是代码气味。可以说,您制作了使用MyLabel的类库。因为它从Label继承,所以我知道我可以像标签一样使用它。然后,当我这样做时:

MyLabel myLanta = new MyLabel();
myLanta.Text = "Oh!";

...然后,我将花一个小时尝试找出为什么迈兰塔的文字总是"不!"的原因。这就是为什么在此处提出例外的原因很重要,或者至少使用摘要,因此当另一个人进行编码时,他们可以看出,无论他们为"文本"分配了什么,它都会始终是" nope"。

我的建议是,如果您需要缩小类的可用属性,使该类成为新类的组成部分,而不是继承

public class MyLabel
{
    private System.Windows.Forms.Label label 
    = new System.Windows.Forms.Label { Text = "Nope", BackColor = Color.Green };
    //a public accessor and setter
    public Font Font { get { return label.Font; } set { label.Font = value; } }     
    //only this class can set the color, any class can read the color
    public Color ForeColor { get { return label.ForeColor; } private set { label.ForeColor = value; } }
    public AllMyStuffIWantToDo()....
    //fill in your stuff here
}

然后,如果要返回Label的属性,则可以使用所控制的方法和属性,而不必担心继承问题。如果您不提供Label属性的访问方法,则该属性永远不会看到一天的光线,并且实际上是私人的。这也可以防止损坏的代码无法通过您的MyLabel代替Forms.Label,因为该继承合同将不存在。

最新更新