好奇的情况:
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
}
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.
问题:
==
Height
?答案 0 :(得分:1)
什么时候有用?我真的不认为用这种方式隐藏成员是个好主意。这只会导致维护噩梦 - 当你看到“高度”时,你不能轻易分辨出它真正指的是哪个成员。
IMO,“new”应该只用作最后的绝望行为,通常是在基类引入了与您现有的一个成员冲突的成员时。它不应该被用作故意避免正常OO设计原则的方式。