开发者

Does private mean different things in C++ and C#?

开发者 https://www.devze.com 2023-01-27 10:18 出处:网络
I was wondering why C# doesn\'t allow private virtual functions and ran across the aptly named Why are private virtual methods illegal in C#?

I was wondering why C# doesn't allow private virtual functions and ran across the aptly named Why are private virtual methods illegal in C#?

In the accepted answer Eric Lippert (who probably knows what he's talking about...) said:

If you desire to restrict the ability to override the method 开发者_StackOverflowin non-nested derived classes then you can do so by restricting the ability of non-nested classes to derive from the base class;

In C++ private: virtual makes sense because it means "I want classes derived from me to override the functionality of this function but they shouldn't be able to call it directly", in other words private controls who can call a function and has no effect on who can override it.

I realize that since only derived classes can override in the first place and since C# prohibits private virtual functions this question may be meaningless, are there other scenarios in which the protection level of a function can effect who can override it (protected internal perhaps)?


It sounds like you want the C++ world of being able to override but not call; then no: you can't do that in C#. The other way around is fine, though - either don't mark it virtual in the first place, or mark it sealed if it is already virtual.

0

精彩评论

暂无评论...
验证码 换一张
取 消