- 先看看下边的代码:
class Program
{
static void Main( string [] args)
{
Nullable < int > a = 1 ;
Console.WriteLine(a.GetType().ToString());
Console.Read();
}
} - 对于初学者来说,往往会认为这段程序运行的结果是如下:
System.Nullable` 1 [System.Int32]
- 但运行的结果却是如下:
System.Int32
- 我们先用反汇编程序查看下:
IL_000a: ldloc. 0
IL_000b: box valuetype [mscorlib]System.Nullable` 1 < int32 >
IL_0010: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
IL_0015: callvirt instance string [mscorlib]System.Object::ToString()
IL_001a: call void [mscorlib]System.Console::WriteLine( string ) - 从中我们会发现,当我们调用GetType()方法的时候,a对象先进行了装箱(box),在托管堆的对象是Int32类型。
在.NET中,值类型对象在调用GetType()方法的时候,都需要先进行装箱操作。
转载于:https://www.cnblogs.com/flashpast/archive/2009/10/24/1589307.html