A boxing conversion is the implicit conversion of a value type to an object type, or the conversion of the value type to an interface type applied by the value type (interface-type). Boxing the value of a value type, that is, creating an instance of object and copying that value to this object, for example:
int i=10;
Object obj=i;
Use the following figure to represent the boxing process:
We can also use the explicit method for boxing operations:
int i=10;
Object Obj=object (i);
We can assume that there is a boxing type, and its declaration is as follows:
Class T_box
{
T value;
T_box (Tt) {
value=t;
}//The constructor of this type
}
Here T represents the type of value that will be boxed, it can be int, char, enum, and so on. Now we're going to boxing the value V of type T, which executes the following: Execute new T_box (v), which returns an instance of the result as the value of the object type, and then the statement:
int i=10;
Object obj=i;
Equivalent to:
int i=10;
Object Obj=new Int_box (i); Loading I boxing into object obj
Let's take a look at the following procedure.
Program Listing 4-4:
Using System
class test{public
static void Main () {
int i=10;
Object obj=i; Object Type
if (obj is int) {
Console.Write ("The value of ' I is boxing!");
}
i=20; Change the value of I
Console.WriteLine ("Int:i={0}", i);
Console.WriteLine ("Object:obj={0}", obj);
}
The output result is: The
value of I is boxing!
int:i=20;
object:obj=10;
This proves that the value of the boxed type is assigned to the object as a copy.