开发者

New static fields and hiding the public inherited members

Curious situation:

public class MyTextBox : TextBox
{
    // I want use the same height for all MyTextBoxes
    public new static int Height;
}

public Form1()
{
    InitializeComponent();

    MyTextBox mtb1 = new MyTextBox();
    MyTextBox mtb2 = new MyTextBox();

    mtb1.Multiline = true;
    mtb2.Multiline = true;

   开发者_开发技巧 mtb1.Location = new Point(50, 100);
    mtb2.Location = new Point(200, 100);

    mtb1.Size = new Size(50, 50);
    mtb2.Size = new Size(150, 150);

    Controls.Add(mtb1);
    Controls.Add(mtb2);

    mtb1.Text = mtb1.Height;
    mtb2.Text = mtb2.Height;
    // Error 1 Member 'WindowsFormsApplication9.MyTextBox.Height'
    // cannot be accessed with an instance reference;
    // qualify it with a type name instead
}

The same thing in VB.NET

Public Class MyTextBox
    Inherits TextBox
    Public Shared Shadows Height As Integer
End Class

mtb1.Text = mtb1.Height ' Text will be "0" '
'Warning 1   Access of shared member, constant member, enum member or nested '
' type through an instance; qualifying expression will not be evaluated.

Questions:

==

  1. Couldn't this method be used to hide the public members in the inherited classes? Sometimes this can be useful...
  2. How can I use same Height for all members?


When would it be useful? I really don't think it's a good idea to hide members in this way. It's just going to cause a maintenance nightmare - when you see "Height" you can't easily tell which member it's really referring to.

IMO, "new" should only be used as a last act of desperation, usually if a base class has introduced a member which clashes with one of your existing ones. It shouldn't be used as a way of deliberately avoiding normal OO design principles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜