Difference between new and override

后端 未结 14 1737
再見小時候
再見小時候 2020-11-22 05:36

Wondering what the difference is between the following:

Case 1: Base Class

public void DoIt();

Case 1: Inherited class

<         


        
14条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:11

    At the first case it will call derived class DoIt() method because new keyword hides base class DoIt() method.

    At the second case it will call overriden DoIt()

      public class A
    {
        public virtual void DoIt()
        {
            Console.WriteLine("A::DoIt()");
        }
    }
    
    public class B : A
    {
        new public void DoIt()
        {
            Console.WriteLine("B::DoIt()");
        }
    }
    
    public class C : A
    {
        public override void DoIt()
        {
            Console.WriteLine("C::DoIt()");
        }
    }
    

    let create instance of these classes

       A instanceA = new A();
    
        B instanceB = new B();
        C instanceC = new C();
    
        instanceA.DoIt(); //A::DoIt()
        instanceB.DoIt(); //B::DoIt()
        instanceC.DoIt(); //B::DoIt()
    

    Everything is expected at above. Let set instanceB and instanceC to instanceA and call DoIt() method and check result.

        instanceA = instanceB;
        instanceA.DoIt(); //A::DoIt() calls DoIt method in class A
    
        instanceA = instanceC;
        instanceA.DoIt();//C::DoIt() calls DoIt method in class C because it was overriden in class C
    

提交回复
热议问题