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:
==
- Couldn't this method be used to hide the public members in the inherited classes? Sometimes this can be useful...
- 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.
精彩评论