Why are private virtual methods illegal in C#?

后端 未结 6 565
轮回少年
轮回少年 2020-12-02 13:05

Coming from a C++ background, this came as a surprise to me. In C++ it\'s good practice to make virtual functions private. From http://www.gotw.ca/publications/mill18.htm: \

6条回答
  •  我在风中等你
    2020-12-02 13:44

    Let me make this clear: C# is not C++.

    C# is designed multiple decades after C++ and is built using advancing insights over the years. In my humble opinion C# is well defined and finally handles object orientation the right way (imho). It includes the internal statement for a reason and does not allow you to "virtualize" and override private methods. For a reason.

    All the issues described earlier (inner classes overriding private virtual methods, using the abstract factory pattern this way etc...) can be easily written in a different way using interfaces and the internal statement. Having said that, I must say that it is fairly a matter of taste whether you like the C++ way or the C# way.

    I prefer to use descriptive code (code that speaks for itself, without using comments) and I use interfaces instead of deep inheritance. Overriding private virtual methods feels like hacking or spaghetti to me, regardless if it's common practice, an often used pattern or gets the job done.

    I've been developing in C++ for almost 1.5 decades and I never came across the necessity for overriding private methods... ( I can see the comments flying in :-) )

提交回复
热议问题