Knowledge Points: Reference types, value types, boxing, unpacking
The CLR supports two types: reference types and value types. The reference type allocates memory on the heap, and the value type allocates memory on the thread stack. The value types and reference types are as follows:
There are two representations of value type objects: unboxed and boxed. A variable of one value type is paid to another value type variable, and a verbatim segment copy is performed.
Boxing : Converting a value type to a reference type is called boxing. The following actions occur in boxing:
1. Allocate good memory in the managed heap. The allocated memory size equals the amount of memory that is required for each field of the value type, plus the number of memory required for the type object pointer and the synchronization block index.
2. The value type of the field is copied to the newly allocated heap memory.
3. Returns the address of the object.
unpacking : Converting a reference type to a value type, first the memory allocation of the value type in the thread stack, and the memory allocation of the reference type in the managed heap, so all the fields in the reference type need to be copied to the line stacks. The CLR completes this copy operation in two steps.
1. Gets the address of each field in the boxed object. This process is called unpacking.
2. Copy the values contained in these fields from the managed heap to the line stacks.
Use the following example to gain an in-depth understanding of boxing and unpacking:
Internal structPoint {Private int_x, _y; PublicPoint (intx =0,inty =0) {_x=x; _y=y; } Public voidChange (intx =0,inty =0) {_x=x; _y=y; } Public Override stringToString () {return string. Format ("{0},{1}", _x,_y); } } classProgram {Static voidMain (string[] args) {Point P=NewPoint (x:1Y:1); Console.WriteLine (P); P.change (x:2Y:2); Console.WriteLine (P); Object o=p; Console.WriteLine (o); (point) O). Change (x:3Y:3); //What is the result of this execution? Why? Console.WriteLine (o); Console.ReadLine (); } }
CLR value types and reference types