问题
As the reference values are stored in the heap as a data; where do the type information of any reference value is stored?
If there are a couple of instances of class Artist; when they are stored in the heap how the .Net tags those memory blocks as type of Artist?
thanks!
回答1:
void M()
{
Artist a = new Artist();
}
When the method is called, a new stack frame is expanded, CLR has some preparation code before the first statement of the method is executed, like a prolegomenon. During this period, CLR loads all types used in the method. In this example, type of Artist
will be loaded to heap. But it is also possible that the type is already there, because the type is used before M()
is invoked. Then we come to the first expression, a new
statement, which invokes the constructor of the class. If you take a look at the CIL it generated, you will see something like newobj
blabla. Here a block of memory on the heap are allocated for the storage of the instance. The size of the block depends on the details of the class, because the block needs to hold all the data of the instance. Usually the block is made up by:
Type pointer + Sync root + Instance data
The type pointer points to its type on the heap(loaded in the prolegomenon). The sync root is a record for lock and synchronization. The instance data stores the members' data of the instance.
回答2:
The CLR stores a couple of bits of information alongside the data in your object instance. One of these is a pointer to the Type of the object.
回答3:
Just before a class is used for the first time the dotnet runtime creates an object on the heap that stores all the information about the class to be used. This includes static fields, a method table that points to the methods the class has available, a type object pointer (more on this in a second) and a sync block (used for locking the object).
All objects have a type object pointer which points to an object that stores the information about the class.
So, for instance, if you have a Person object it will have a type object pointer that points to an object on the heap which stores all the information about person. This person Type object will also have a type object pointer which points to an object of System.Type as it's type is System.Type (it's an object that stores information about the type of an object).
Of course System.Type, being an object on the heap also has a type object pointer which points to the information on what type it is. As you've probably guessed - it points to itself as the System.Type object is a System.Type object.
When you call GetType() on an object it just returns the address stored in the specific objects type object pointer.
来源:https://stackoverflow.com/questions/5946402/where-the-type-of-a-reference-value-is-stored-in-memory