方法重载解析和 Jon Skeet 的脑筋急转弯
这里有剧透...
我我正在查看 #1 的答案,我必须承认我从来不知道重载解析中是这种情况。但为什么会是这样呢。在我小小的头脑中 Derived.Foo(int)
似乎是顺理成章的走下去的路线。
这个设计决策背后的逻辑是什么?
奖励时间!
此行为是 C# 规范、CLR 实现还是编译器的结果吗?
Here Be Spoilers...
I'm looking at the answer to #1, and I must admit I never knew this was the case in overload resolution. But why is this the case. In my tiny mind Derived.Foo(int)
seems like the logical route to go down.
What is the logic behind this design decision?
BONUS TIME!
Is this behaviour a result of the C# specification, the CLR implementation, or the Compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下是一个可能的解释:
当编译器链接方法调用时,它首先在继承链中最低的类(在本例中为
Derived
类)中查找。它的实例方法被检查和匹配。重写的方法 Foo 不是Derived
的实例方法,而是Base
类的实例方法。正如 Jack30lena 提出的那样,原因可能是性能,但也可能是编译器如何解释编码器的意图。可以肯定的是,开发人员的预期代码行为位于继承链底部的代码中。
Here is a possible explanation:
When the compiler links the method calls, the first place it looks in in the class that is lowest in the inheritance chain (in this case the
Derived
class). It's instance methods are checked and matched. The overridden method Foo is not an instance method ofDerived
, it is an instance method of theBase
class.The reason why could be performance, as Jack30lena proposed, but it could also be how the compiler interprets the coder's intention. It's a safe assumption that the developer's intended code behavior lies in the code at the bottom of the inheritance chain.
这是编译器的结果,我们检查了 IL 代码。
It's a result of the compiler, we examined the IL code.
原因是因为它是模糊的。编译器只需决定其中之一。有人认为间接性越少越好(性能可能是一个原因)。
如果开发人员只是写:
它很清楚并且给你预期的结果。
The reason is because it is ambiguous. The compiler just has to decide for one. And somebody thought that the less indirect one would be better (performance might be a reason).
If the developer just wrote:
it's clear and giving you the expected result.
原因就是:性能。
调用虚方法需要更多时间。在虚拟方法上调用委托需要更多时间等等......
请参阅:
方法调用的成本
the reason is: performance.
calling a virtual method takes a bit more time. calling a delegate on a virtual method takes much more time and so on....
see:
The cost of method calls
这种行为是经过深思熟虑和精心设计的。原因是因为此选择减轻了一种形式的脆弱基类故障的影响。
请阅读我关于该主题的文章以了解更多详细信息。
https://learn.microsoft。 com/en-us/archive/blogs/ericlippert/future-writing-changes-part-third
This behaviour is deliberate and carefully designed. The reason is because this choice mitigates the impact of one form of the Brittle Base Class Failure.
Read my article on the subject for more details.
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/future-breaking-changes-part-three