CLR value type and reference type. clr value reference
Knowledge Point: reference type, value type, packing, and unpacking
CLR supports two types: reference type and value type. The reference type is allocated memory on the stack, and the value type is allocated memory on the thread stack. The value type and reference type are as follows:
A Value Type object can be expressed in two forms: unboxed and boxed. If you pay a value type variable to another value type variable, a field-by-field copy is performed.
Packing: Converts a value type to a reference type called packing. The following operations occur when packing:
1. allocate memory in the managed heap. The allocated memory size is equal to the memory size required for each field of the Value Type plus the memory size required for the Type object pointer and synchronization block index.
2. Copy the value type field to the newly allocated heap memory.
3. The address of the returned object.
Unpack: Converts a reference type to a value type. First, the memory of the value type is allocated to the thread stack, and the memory of the reference type is allocated to the managed stack, therefore, all fields of the reference type must be copied to the thread stack. CLR completes the replication operation in two steps.
1. Obtain 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 thread stack.
The following example provides an in-depth understanding of packing and unpacking:
Internal struct Point {private int _ x, _ y; public Point (int x = 0, int y = 0) {_ x = x; _ y = y ;} public void Change (int x = 0, int y = 0) {_ x = x; _ y = y;} public override string ToString () {return string. format ("{0}, {1}", _ x, _ y) ;}} class Program {static void Main (string [] args) {Point p = new Point (x: 1, y: 1); Console. writeLine (p); p. change (x: 2, y: 2); Console. writeLine (p); Object o = p; Conso Le. WriteLine (o); (Point) o). Change (x: 3, y: 3); // What is the execution result? Why? Console. WriteLine (o); Console. ReadLine ();}}