2012-05-25 45 views
2

有沒有辦法隱藏基類的成員?'刪除'基本成員?

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; 
    } 
} 
+5

沒有。 [C#歸因於LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle)。可以做的最好的事情是拋出異常;或者在某些情況下使用更精細的接口。 – 2012-05-25 02:27:36

+0

@pst:Eric Lippert在一些討論中已經很清楚地表明C#中的子類型不使用Liskov定義。 –

+3

我很好奇爲什麼你會想要這樣做。 – casablanca

回答

1

沒有辦法在C#語言中隱藏成員。您可以得到的最接近的結果是使用EditorBrowsableAttribute來隱藏編輯的成員。

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

我敢說,沒有guaruntee,這將其他編輯比Visual Studio的工作,所以你最好在它的上面拋出異常。

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

這就是我最初的想法,我只是想確保它沒有語言層面的手段。 – Shimmy