【问题标题】:'Delete' base member?“删除”基地成员?
【发布时间】:2012-05-25 02:25:27
【问题描述】:

有没有办法隐藏基类的成员?

class A
{
  public int MyProperty { get; set; }
}

class B : A
{
  private new int MyProperty { get; set; }
}

class C : B
{
  public C()
  {
    //this should be an error
    this.MyProperty = 5;
  }
}

【问题讨论】:

  • 没有。那没有。 C# ascribes to the LSP。能做的最好的就是抛出异常;或者在某些情况下使用更精细的接口。
  • @pst:Eric Lippert 在几次讨论中向我明确表示,C# 中的子类型化不使用 Liskov 定义。
  • 我很好奇你为什么要这样做。
  • @BenVoigt 我有兴趣阅读有关该主题的资源。每当我想到 LSP 时,我通常只考虑一种温和的形式(例如,主要是签名,不一定是不变量或它涵盖的所有其他语义)。
  • @casablanca,我想这样做,因为我覆盖了一个提供许多覆盖方法的基类,其中一个使用了一个属性,我省略了该属性的用法,所以我想关于删除它。

标签: c# inheritance polymorphism shadow member-access


【解决方案1】:

在 C# 语言中没有隐藏成员的方法。最接近的方法是使用 EditorBrowsableAttribute 对编辑器隐藏成员。

public class B : A
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    new public int MyProperty {
        get;
        set;
    }
}

我敢说,除了 Visual Studio 之外,不能保证这适用于其他编辑器,因此最好在其上抛出异常。

public class B : A
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public new int MyProperty {
        get {
            throw new System.NotSupportedException();
        }
        set {
            throw new System.NotSupportedException();
        }
    }
}

【讨论】:

  • 这就是我最初的想法,我只是想确保它没有语言级别的手段。
猜你喜欢
  • 2017-01-10
  • 2019-10-19
  • 2014-10-05
  • 2018-12-18
  • 2013-02-26
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多