日期:2014-05-18  浏览次数:20836 次

c#的一个装箱和拆箱的问题
在C#中,可以通过装箱和拆箱实现值类型与引用类型之间相互转换,在下列代码中,有()处实现了装箱
int age = 5;
object o = age;
o = 10;
age = (int)o;
object oAge = age;


------解决方案--------------------
3
------解决方案--------------------

object o = age; 
o = 10; 
object oAge = age; 

------解决方案--------------------
简单一点的理解,装箱,就是变成一个通用对像(Object),拆箱就是从Object,转换成你想要的对像

------解决方案--------------------
哪三个呢,
============================

object o = age;
o = 10;
object oAge = age;
------解决方案--------------------
C# code

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的。