What if I don't heed the warning “hides inherited member. To make the current member override that implementation…”

前端 未结 3 1286
既然无缘
既然无缘 2021-02-02 07:36

This is maybe a fine point, but it concerns the warning that the compiler issues if you do something like:

class A
{
    public virtual void F() { }
}
class B :          


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 08:16

    It will not do anything but the method you have there F() is also not polymorphic. It becomes very easy to make mistake in code if you started to use base class reference hence you are warned. Of course it can be what you want, hence the new keyword just make it more explicit

    E.g.

    B b1 = new B();
    b1.F(); // will call B.F()
    
    A b2 = new B();
    b2.F(); // will call A.F()
    

    Now, if you add class C with new, it will behave the same as B. If you add class D with override, then F becomes polymorphic:

    class C : A
    {
        public new void F() { }
    }
    
    class D : A
    {
        public override void F() { }
    }
    
    // Later
    
    C c1 = new C();
    c1.F(); // will call C.F()
    
    A c2 = new C();
    c2.F(); // will call A.F()
    
    D d1 = new D();
    d1.F(); // will call D.F()
    
    A d2 = new D();
    d2.F(); // will call D.F()
    

    See this fiddle.

提交回复
热议问题