日期:2014-05-18 浏览次数:20836 次
int age = 5; object o = age; //装箱1 o = 10; //装箱2 age = (int)o; object oAge = age; //装箱3
------解决方案--------------------
算了,我还是写明了吧,不知道为什么有这么多人同意是2次boxing,我们来把这段C#代码转换成IL代码,如下:
.locals init ([0] int32 age,
[1] object o,
[2] object oAge)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: box [mscorlib]System.Int32
IL_0009: stloc.1
IL_000a: ldc.i4.s 10
IL_000c: box [mscorlib]System.Int32
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: unbox.any [mscorlib]System.Int32
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: box [mscorlib]System.Int32
IL_001f: stloc.2
看行IL_0004, IL_000c和IL_001a,非常明确的3次boxing。不要以为o = 10;那一行直接就产生了object 10,一样要box的。