我创建了一个简单的C#
程序:
class Program
{
static void Main(string[] args)
{
Int32? a = null;
object x = a;
}
}
根据 MSDN:
基于可空类型的对象仅在对象非空时才被装箱。如果 HasValue 为 false,则将对象引用分配给 null而不是装箱。
我已经尝试了我的可执行文件,ILDASM
发现IL
代码调用了box方法。
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 17 (0x11)
.maxstack 1
.locals init ([0] valuetype [mscorlib]System.Nullable`1<int32> a,
[1] object x)
IL_0000: nop
IL_0001: ldloca.s a
IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0009: ldloc.0
IL_000a: box valuetype [mscorlib]System.Nullable`1<int32>
IL_000f: stloc.1
IL_0010: ret
} // end of method Program::Main
我的问题是:为什么叫它?也许我做错了什么或误解了什么?