WHy should virtual methods be explicitly overridden in C#?

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

Why should virtual methods be explicitly overridden in C#?

5条回答
  •  悲哀的现实
    2021-02-20 02:35

    It is because the C# team members are all skilled C++ programmers. And know how incipient this particular bug is:

    class Base {
    protected:
        virtual void Mumble(int arg) {}
    };
    
    class Derived : public Base {
    protected:
        // Override base class method
        void Mumble(long arg) {}
    };
    

    It is a lot more common then you might think. The derived class is always declared in another source code file. You don't typically get this wrong right away, it happens when you refactor. No peep from the compiler, the code runs pretty normal, just doesn't do what you expect it to do. You can look at it for an hour or a day and not see the bug.

    This can never happen in a C# program. Even managed C++ adopted this syntax, breaking with native C++ syntax intentionally. Always a courageous choice. IntelliSense takes the sting out the extra verbiage.

    There's a lot of syntax tweaks in C# that resemble this kind of bug avoidance syntax.


    EDIT: and the rest of the C++ community agreed and adopted the override keyword into the new C++11 language specification.

提交回复
热议问题