How CLR calls methods correctly hidden by derived class when reference is stored in a base class variable?

拈花ヽ惹草 提交于 2019-12-12 11:58:29

问题


I am trying to understand how CLR dispatches method call correctly when an object hides base class member when object reference is stored in a base class variable.

The point of my confusion is the object header created by runtime. The object header on heap has two fields: Type pointer and Sync block index. The type pointer points to the method table of the class. Even if the object reference is of base class, the object created on heap is of derived class. This should cause runtime to use method table of derived class object. But the runtime calls the base class member correctly.

Could you please help me in understanding the flow as how does CLR calls the methods correctly in this scenario?


回答1:


The object type as recorded in the object header doesn't matter here. The compiler emits the method call naming the specific class whose method should be called. Quite visible in the generated IL. For example:

class Base {
    void foo() { }
    void callFoo() {
        foo();         // <== here
    }
}
class Derived : Base {
    new void foo() { }
}

The indicated statement generates this IL:

IL_0002:  call       instance void ConsoleApplication1.Base::foo()

Note the presence of Base in the call opcode, there is no ambiguity.




回答2:


Calling a method that is not virtual or overridden in any way has nothing to do with the method table. The C# compiler calls that method by name (the assembly really contains the name as a string!) and the JIT hard-codes the address of the function into the emitted x86 code. The address does not depend on the runtime type of the this object reference.



来源:https://stackoverflow.com/questions/12017538/how-clr-calls-methods-correctly-hidden-by-derived-class-when-reference-is-stored

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!