【问题标题】:New static fields and hiding the public inherited members新的静态字段并隐藏公共继承成员
【发布时间】:2011-01-12 13:36:20
【问题描述】:

好奇的情况:

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.

问题:

==

  1. 这个方法不能 用于隐藏 继承的公共成员 上课?有时这可能是 有用...
  2. 如何为所有成员使用相同的Height

【问题讨论】:

标签: c# .net vb.net inheritance


【解决方案1】:

什么时候有用?我真的不认为以这种方式隐藏成员是一个好主意。这只会导致维护噩梦 - 当您看到“身高”时,您无法轻易分辨出它真正指的是哪个成员。

IMO,“新”只能用作最后的绝望行为,通常是在基类引入的成员与您现有的成员发生冲突的情况下。它不应该被用作故意避免正常 OO 设计原则的一种方式。

【讨论】:

  • 好的,所有文本框的高度都一样吗?或者我应该重命名该字段?
  • @serhio:绝对要重命名该字段 - 如果您确实需要一个字段。
  • @Jon Skeet:如果基类提供了一个不应提供给特定派生类的后代(例如 MemberwiseClone)的受保护成员怎么办?通过使用显然不应该使用的东西(例如,枚举类型 DontTryThis 的 WriteOnly 属性,其唯一定义的值是 DontTryThis.NoReallyDont)来隐藏受保护的成员似乎比让它可用允许它被错误地调用更好。专门用于简单地隐藏继承方法的关键字可能会更好,但我不知道 vb.net 或 C# 中的关键字。
  • @supercat:如果基类提供了一个受保护的成员,那么它应该对所有派生类都是可见的。否则,它违反了 Liskov 的替代原则。基本上这是糟糕的设计——不要用“新”贴在上面。
  • @Jon Skeet:LSP 对于类的公共成员很重要,因为派生自 'bar' 的派生类 'foo' 可能会传递给一些需要 'bar' 的代码。如果不能用 'foo' 代替 'bar',这样的代码就会中断。这种多态性不是受保护方法的问题。如果类 'foo' 继承自 'bar',则 foo 对象的基础将是 'bar'。时期。没有办法从'bar'继承一些其他类并以某种方式成为 foo 的基础。碱基不能被替换的事实是首先拥有受保护成员的重要原因。
猜你喜欢
  • 2015-07-15
  • 2012-02-13
  • 2010-09-05
  • 2011-10-10
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
相关资源
最近更新 更多