WHy should virtual methods be explicitly overridden in C#?

前端 未结 5 1725
遇见更好的自我
遇见更好的自我 2021-02-20 02:08

Why should virtual methods be explicitly overridden in C#?

5条回答
  •  一整个雨季
    2021-02-20 02:25

    If you don't add the override keyword, the method will be hidden (as if it had the new keyword), not overridden.

    For example:

    class Base {
        public virtual void T() { Console.WriteLine("Base"); }
    }
    class Derived : Base {
        public void T() { Console.WriteLine("Derived"); }
    }
    
    Base d = new Derived();
    d.T();
    

    This code prints Base. If you add override to the Derived implementation, the code will print Derived.

    You cannot do this in C++ with a virtual method. (There is no way to hide a C++ virtual method without overriding it)

提交回复
热议问题