Difference between new and override

后端 未结 14 1522
再見小時候
再見小時候 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条回答
  •  再見小時候
    2020-11-22 06:00

    In case 1 if you used call the DoIt() method of the inherited class while the type is declared as the base class you will see the action of the base class even.

    /* Results
    Class1
    Base1
    Class2
    Class2
    */
    public abstract class Base1
    {
        public void DoIt() { Console.WriteLine("Base1"); }
    }
    public  class Class1 : Base1 
    {
        public new void DoIt() { Console.WriteLine("Class1"); }
    }
    public abstract class Base2
    {
        public virtual void DoIt() { Console.WriteLine("Base2"); }
    }
    public class Class2 : Base2
    {
        public override void DoIt() { Console.WriteLine("Class2"); }
    }
    static void Main(string[] args)
    {
        var c1 = new Class1();
        c1.DoIt();
        ((Base1)c1).DoIt();
    
        var c2 = new Class2();
        c2.DoIt();
        ((Base2)c2).DoIt();
        Console.Read();
    }
    

提交回复
热议问题