CLR是如何调用正确隐藏由派生类方法时参考存储在一个基类变量? [英] How CLR calls methods correctly hidden by derived class when reference is stored in a base class variable?

查看:221
本文介绍了CLR是如何调用正确隐藏由派生类方法时参考存储在一个基类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解CLR如何分派方法调用正确当一个对象隐藏了​​基类成员时,对象引用存储在一个基类的变量。

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.

能否请你帮我理解流为如何CLR调用正确的方法,在这种情况下?

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

推荐答案

为记录对象头中的对象类型并不重要位置。编译器发出方法调用命名的方法应该被称为特定类。非常明显在生成的IL。例如:

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() { }
}

指示的语句就会产生这种IL:

The indicated statement generates this IL:

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

请注意相应的呼叫运code中的presence,没有歧义。

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

这篇关于CLR是如何调用正确隐藏由派生类方法时参考存储在一个基类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆