Calling GetType()
on a value type boxes that value type. By moving the value type onto the heap you now have a reference type which now has a pointer to the type of that object.
If you wish to avoid boxing you can call GetTypeCode
which returns an enumeration that indicates the type of the value type without boxing it.
Here is an example showing the boxing that takes place:
C#:
class Program
{
static void Main()
{
34.GetType();
}
}
IL for Main()
:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: ldc.i4.s 0x22
L_0002: box int32
L_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_000c: pop
L_000d: ret
}
Edit: To show what the compiler is doing, lets change the type of the literal like this:
class Program
{
static void Main()
{
34L.GetType();
}
}
By adding the "L"
after the literal I am telling the compiler that I want this literal to be converted to a System.Int64
. The compiler sees this and when it emits the box
instruction it looks like this:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: ldc.i4.s 0x22
L_0002: conv.i8
L_0003: box int64
L_0008: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_000d: pop
L_000e: ret
}
As you can see, the compiler has done the hard work of determining the correct instructions to emit, after that it is up to the CLR to execute them.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…