Difference between new and override

后端 未结 14 1660
再見小時候
再見小時候 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 05:58

    Out of all those, new is the most confusing. Through experimenting, the new keyword is like giving developers the option to override the inheriting class implementation with the base class implementation by explicitly defining the type. It is like thinking the other way around.

    In the example below, the result will return "Derived result" until the type is explicitly defined as BaseClass test, only then "Base result" will be returned.

    class Program
    {
        static void Main(string[] args)
        {
            var test = new DerivedClass();
            var result = test.DoSomething();
        }
    }
    
    class BaseClass
    {
        public virtual string DoSomething()
        {
            return "Base result";
        }
    }
    
    class DerivedClass : BaseClass
    {
        public new string DoSomething()
        {
            return "Derived result";
        }
    }
    

提交回复
热议问题