Virtual method tables

别等时光非礼了梦想. 提交于 2019-11-27 04:04:42

问题


When discussing sealed classes, the term "virtual function table" is mentioned quite frequently. What exactly is this? I read about a method table a while ago (I don't remember the purpose of the purpose of this either) and a google/search on here brings up C++ related results.

Thanks


回答1:


The C# virtual function table works basically the same as the C++ one, so any resources which describe how the C++ virtual function table works should help you pretty well with the C# one as well.

For example, Wikipedia's description is not bad.




回答2:


The "virtual function table" or "virtual method table" is a list of method pointers that each class has. It contains pointers to the virtual methods in the class.

Each instance of a class has a pointer to the table, which is used when you call a virtual method from the instance. This is because a call to a virtual method should call the method associated with the class of the actual object, not the class of the reference to the object.

If you for example have an object reference to a string:

object obj = "asdf";

and call the virtual method ToString:

string text = obj.ToString();

it will use the String.ToString method, not the Object.ToString method. It's using the virtual method table of the String class (which the pointer in the string instance is pointing to), not the virtual method table of the Object class.




回答3:


The definition for Virtual Function Table (often call vtable) is the same in C# and C++. It is an lookup table use internally by the runtime to achieve the polymorphic behaviors of abstract/virtual/override method.

In simple you can imagine a base class with a virtual methodA will have a vtable that contains methodA. When derived class override methodA, the vtable for methodA inherits from the parent class but will now points to the methodA in the derived class rather than parent class.



来源:https://stackoverflow.com/questions/2413483/virtual-method-tables

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