Method overloads resolution and Jon Skeet's Brain Teasers

前端 未结 5 1533
無奈伤痛
無奈伤痛 2020-12-13 06:45

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 resol

相关标签:
5条回答
  • 2020-12-13 07:28

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

    0 讨论(0)
  • 2020-12-13 07:34

    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

    0 讨论(0)
  • 2020-12-13 07:37

    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.

    0 讨论(0)
  • 2020-12-13 07:38

    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.

    0 讨论(0)
  • 2020-12-13 07:41

    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.

    http://blogs.msdn.com/ericlippert/archive/2007/09/04/future-breaking-changes-part-three.aspx

    0 讨论(0)
提交回复
热议问题