If I assign a simple value type (e.g. an int) to an attribute of type ValueT开发者_运维知识库ype, is the value then boxed?
For example if I do this:
int i = 4;
ValueType test = i;
Will the value be boxed?
Yes, it will. This is because each type occupies a constant amount of memory at runtime (int
takes 4 bytes, for example). A struct will take as much space is required to lay out all of the fields in memory.
Since you can store any value type in ValueType
, and since ValueType
would have to be exactly the same size as the type you're assigning to test
, the ValueType
type is actually a reference type.
Consider:
int a = 0;
long b = 1;
ValueType test;
test = a;
test = b;
This is perfectly valid code. test
must occupy a fixed size on the stack, and a
and b
are different sizes. Hopefully this clarifies why exactly ValueType
cannot itself be a value type. (It's related to the reason why you can't derive value types.)
Yes, that will box it - ValueType
is a reference type (a class), confusingly enough :) It's simply the type from which every value type "inherits" (directly in the case of structs, and indirectly in the case of enums).
Boxing occurs any time you assign a value type value to a variable of a reference type, including object
, ValueType
, Enum
and any interfaces. (It also occurs when use a value type value as an argument where the parameter is one of those types, etc.)
ValueType
is a reference type. The IL generated on this assignment actually boxes the struct.
Here is an example of a box instruction when assigning to object:
void Main()
{
object o = 1;
Console.Write(o);
}
IL_0000: ldc.i4.1
IL_0001: box System.Int32
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call System.Console.Write
And when assigning to ValueType
:
void Main()
{
ValueType o = 1;
Console.Write(o);
}
IL_0000: ldc.i4.1
IL_0001: box System.Int32
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call System.Console.Write
精彩评论