方法重载解析和 Jon Skeet 的脑筋急转弯

发布于 2024-08-30 12:20:14 字数 436 浏览 3 评论 0原文

乔恩的脑筋急转弯

这里有剧透...

我我正在查看 #1 的答案,我必须承认我从来不知道重载解析中是这种情况。但为什么是这样呢。在我小小的头脑中 Derived.Foo(int) 似乎是顺理成章的走下去的路线。

这个设计决策背后的逻辑是什么?

奖励时间!

此行为是 C# 规范、CLR 实现还是编译器的结果吗?

Jon's Brain Teasers

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

百善笑为先 2024-09-06 12:20:16

以下是一个可能的解释:

当编译器链接方法调用时,它首先在继承链中最低的类(在本例中为 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 of Derived, it is an instance method of the Base 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.

清醇 2024-09-06 12:20:16

这是编译器的结果,我们检查了 IL 代码。

It's a result of the compiler, we examined the IL code.

走过海棠暮 2024-09-06 12:20:16

原因是因为它是模糊的。编译器只需决定其中之一。有人认为间接性越少越好(性能可能是一个原因)。
如果开发人员只是写:

((Base)d).Foo (i);

它很清楚并且给你预期的结果。

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:

((Base)d).Foo (i);

it's clear and giving you the expected result.

情感失落者 2024-09-06 12:20:16

原因就是:性能。
调用虚方法需要更多时间。在虚拟方法上调用委托需要更多时间等等......

请参阅:
方法调用的成本

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

动听の歌 2024-09-06 12:20:15

这种行为是经过深思熟虑和精心设计的。原因是因为此选择减轻了一种形式的脆弱基类故障的影响。

请阅读我关于该主题的文章以了解更多详细信息。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文