如何在c ++和c#中实现vtables?

chr*_*ris 5 c# c++ inheritance interface vtable

让我们有这种情况(在c ++中,在c#类A中,B是接口):

class A { virtual void func() = 0; };
class B { virtual void func() = 0; };
class X: public A, public B { virtual void func(){ var = 1; } int var;};

X * x = new X; // from what I know, x have 2 vtables, is this the same in c#?
A * a = (A*)x; // a == x
B * b = (B*)x; // here b != x, so when calling b->func(), how is the address of var correct?
Run Code Online (Sandbox Code Playgroud)

c#编译器是否始终创建一个vtable?在投射时是否会进行任何指针修正?

Chr*_*lor 3

不想过于迂腐,但 C# 编译器不会参与此级别。整个类型模型、继承、接口实现等实际上由 CLR 处理,更具体地说是 CTS(通用类型系统)。.NET 编译器大多只是生成表示意图的 IL 代码,稍后由 CLR 执行,其中所有 Vtable 处理等都会得到处理。

有关 CLR 如何创建和管理运行时类型的一些详细信息,以下链接将是一个很好的起点。最后解释了方法表和接口映射。

http://web.archive.org/web/20150515023057/https://msdn.microsoft.com/en-us/magazine/cc163791.aspx