Is Richter mistaken when describing the internals of a non-virtual method call?

前端 未结 3 1196
既然无缘
既然无缘 2021-02-07 18:55

I would write this question directly to Jeffrey Richter, but last time he didn\'t answer me :) so I will try to get an answer with your help here, guys :)

In the book \"

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 19:55

    The C# compiler resolves non-virtual methods exactly with no wiggle room. If a derived non-virtual method with the same signature appearch after the caller was compiled, the CLR will still call the "fixed" method the C# compiler chose. This is to avoid the brittle base class problem.

    If you want dynamic method resolution, use virtual. If you don't use virtual you get fully static resolution. Your choice. The runtime type of the object reference becoming the this pointer does not matter in resolution of non-virtual methods at all (neither for csc.exe not for the CLR JIT).

    The JIT will always call the exactly chosen method. It will throw an exception if the method does not exist (maybe because the callee DLL was changed). It will not call a different method.

    callvirt can also call non-virtual methods. It is used to perform a null check. It is defined that way, and C# is defined to perform a null check on every call.

提交回复
热议问题