How does "boxing" work in .NET?
I know what "boxing" is:
object myBox = 5;
Now I wish to increase my knowledge. Is a special type created for this boxing operation? Or is开发者_JAVA技巧 System.Object
used? How does .NET handle boxing?
There is no special type; a boxed value type is an implementation detail of the runtime. But the easiest way to understand it is to imagine that there is a special type:
class Box<T> where T : struct
{
T value;
}
Where the type Box<T>
also implements all the methods, interfaces, and so on, of T, for whatever T happens to be. So, for example, you could imagine that Box<int>
has a method ToString which simply calls int.ToString on the value, and returns the result.
Boxing is simply a mechanism for getting a reference to something that is not of reference type. You just make a box around the thing and get a reference to the box.
The CLR handles boxing.
Consider what happens in this case:
private void myUselessMethod()
{
int i = 5;
object o = i;
}
'i'
is a valueType (an Int32) and, as a local variable, is allocated on the stack ,it allocates only 4 bytes, presumably.
Then, i
is wrapped into an object i.e. boxed.
What the CLR (Common Language Runtime) does:
- It allocates memory on the managed heap: Namely, enough space for an Int32, plus the space for two additional overhead members which every object on the managed heap must have -- the 'type object pointer' and the 'sync index'.
- It copies the value 5 into the newly allocated heap memory.
- It returns the address of the memory in the heap as the reference o.
What I find most confusing about this boxing/unboxing/reference type/value type business is that on one hand, everything is an object, even value types are objects and derive from System.Object
. On the other hand, when an Object is declared, it is always a reference type.
So
void myMethod(System.Object o)
{
doStuff();
}
void myCallingMethod()
{
int i = 5;
myMethod(i);
}
will box i to pass it to myMethod, even though i
is an int, a valueType, and as such perfectly well an object, since value types are derived from System.Object
, too.
As Bala R
mentioned...
there is no better example than the one provided by MSDN
Boxing and Unboxing
精彩评论