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

前端 未结 10 1673
说谎
说谎 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:41

    @Brian R. Bondy pointed me to an interesting article on Hiding through inheritance and the new keyword.

    http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx

    So as workaround I would suggest:

    class BaseClass
    {
        public void A()
        {
            Console.WriteLine("BaseClass.A");
        }
    
        public void B()
        {
            Console.WriteLine("BaseClass.B");
        }
    }
    
    class DerivedClass : BaseClass
    {
        new public void A()
        {
            throw new NotSupportedException();
        }
    
        new public void B()
        {
            throw new NotSupportedException();
        }
    
        public void C()
        {
            base.A();
            base.B();
        }
    }
    

    This way code like this will throw a NotSupportedException:

        DerivedClass d = new DerivedClass();
        d.A();
    

提交回复
热议问题