C# - Can publicly inherited methods be hidden (e.g. made private to derived class)

前端 未结 10 1622
说谎
说谎 2020-12-04 19:00

Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.

e.g.

public DerivedClass : BaseClass {}
<         


        
10条回答
  •  無奈伤痛
    2020-12-04 19:45

    When you, for instance, try to inherit from a List, and you want to hide the direct Add(object _ob) member:

    // the only way to hide
    [Obsolete("This is not supported in this class.", true)]
    public new void Add(object _ob)
    {
        throw NotImplementedException("Don't use!!");
    }
    

    It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:

    error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'

    提交回复
    热议问题