Knowledge points
- The value type.
- The value type allocates memory on the stack, is initialized at declaration time, and cannot be null.
- Value type out of scope system automatically frees memory.
- Mainly consists of two categories: structure, Enumeration (enum), structure is divided into the following categories:
- Integral type (Sbyte, Byte, Char, short, Ushort, Int, Uint, Long, Ulong)
- Floating-point type (float, Double)
- Decimal
- bool
- User-defined structure (struct)
- The reference type.
- The reference type allocates memory in the heap and defaults to NULL when initializing.
- Reference types are recycled through the garbage collection mechanism.
- Includes classes, interfaces, delegates, arrays, and built-in reference types, object and string.
Concept
Because all data types in C # are inherited by the base class System.Object, values of value types and reference types can be converted to and from each other through explicit (or implicit) operations, which are the boxing (boxing) and unboxing (unboxing) processes.
- Boxing is an implicit conversion of a value type to an object type or to any interface type implemented by this value type. Boxing a value type allocates an object instance in the heap and copies the value to the new object.
- unpacking (unboxing) is an explicit conversion from an object type to a value type or from an interface type to a value type that implements the interface. Unboxing operations include:
Check the object instance to make sure it is a boxed value of the given value type. (There is no change to the original type after unpacking, there is no error at compile time, but the operation will be error, so make sure that.) Use GetType (). ToString () Make sure to use the full name of the type, such as: System.String instead of String. )
Copy the value from the instance to the value type variable.
Example
Start by writing a simple console program:
Tutorial_boxing_unboxing.cs
Box packing and unpacking
Using System;
- Class APP
- {
- static void Main ()
- {
- int i = 32;
- Object o = i; Implicit boxing
- Console.WriteLine ("O = {0}", O);
- Console.read ();
- }
- }
Where object o = I here we have a boxing operation, and then we use the MSIL Disassembler to see the internal mechanism of the generated. EXE program.
Principle of packing and unpacking