Through the previous study, we can basically realize the conversion between the value type and the value type, the conversion between the reference type and the reference type, but how is the conversion between the value type and the reference type (object) implemented??
In C #, we use boxing to implement converting a value type to a reference type, using a unboxing implementation to convert a reference type to a value type; in other words, it can implement conversions from any value type to a reference type to an object type, with boxing and unboxing we can treat any type as an object type (The object type can be accessed by clicking the reference type----the object class)
Boxing conversions:
Here I would like to add that in. NET, the data types are divided into value types and references (not equivalent to C + + pointers) types, which correspond to this, memory allocation is divided into two ways, one for the stack, two for the heap, and the managed heap. The value type is only allocated in the stack. The reference type allocates memory to the managed heap.
Write an example:
int i = 123; object o = i; The implementation of the boxing operation, in fact, is also an implicit conversion.
The schematic diagram of the boxing conversion is as follows:
Boxing conversions are essentially a type of replication conversion, meaning that when we have finished boxing, then changing the value of I o will not change
Unboxing conversions:
In contrast to boxing conversions, a unboxing conversion is the conversion of an object type to a value type, and the process of unpacking is divided into two steps, first, checking the object instance to see if he is a boxed value of the given value type, and then copying the value of the instance to a variable of the value type;
Write an example (based on the packing code above):
int n_int = (int) o; To force the conversion of an object type to an int type
You can see that the inverse of the boxing process, the object is cast to the original type, it must be noted that the value of the unboxing must be the same type as the variable to which the target is to be converted.
Here I need to emphasize that boxing and unboxing are conversions from a value type or reference type to an object type, from an object type to a value type or a reference type.
The above is the C # learning Diary----Boxing (boxing) conversion and unpacking (unboxing) conversion content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!