A deep understanding of value type and reference type is the key to. Net developers' long-term success. The following describes the value type and reference type from the perspective of memory layout:
Memory Structure of Value Type:
Memory Structure of the reference type:
An instance of the reference type has two additional fields, syncblockindex and rtti pointer, pointing to a method table structure, therefore, the description of methodtableptr and typeobjectptr are both acceptable. The first version of the book "CLR via C #" marks methodtableptr, and the second version marks typeobjectptr, jeffery thinks typeobjectptr is more accurate.
Besides the object and valuetype types, the value type cannot inherit any other types and cannot be used as the base class of other value types. Therefore, no method table pointer is required in general! When you need to call methods inherited from objects or valuetype, you need a method table pointer. In this case, you need to pack the value type!
Let's look at an example:
Public struct
{
Public overrid string tostring ()
{
Return "A ++ ";
}
}
static void main (string [] ARGs)
{< br> A = new A ();
. tostring (); // it will not be boxed at this time, because the C # compiler finds that struct a overwrites the tostring method, so it will generate an il command to directly call tostring, moreover, it is impossible for a type to inherit from struct a, so the compiler can determine that there will be no polymorphism, so no method table pointer or packing is required!
. getType (); // The box is packed here. Because struct a does not implement the GetType method, you need to call the inherited GetType method. In this case, you need a method table pointer to access the method table, in this case, we need to get it through packing!