关于装箱的一个问题

在《.NET框架程序设计》中有这样的一个例子:

None.gifusing  System;
None.gif
None.gif
struct  Point : ICloneable
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public Int32 x, y;
InBlock.gif
InBlock.gif    
public override String ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("({0}, {1}", x, y);
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public Object Clone()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return MemberwiseClone();
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
public   class  App
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Point p;
InBlock.gif        p.x 
= 10;
InBlock.gif        p.y 
= 20;
InBlock.gif
InBlock.gif        Console.WriteLine(p.ToString());
InBlock.gif        Console.WriteLine(p.GetType());
InBlock.gif
InBlock.gif        Point p2 
= (Point)p.Clone();
InBlock.gif        ICloneable c 
= p2;
InBlock.gif
InBlock.gif        Object o 
= c.Clone();
InBlock.gif
InBlock.gif        p 
= (Point)o;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


里面提到p在执行ToString方法的时候不会发生装箱。通过看IL代码确实是这么回事,但是再去查看Point的ToString方法的IL代码,发现在其中进行了装箱操作,那么是不是总的说来还是进行了装箱操作呢?

IL代码如下:

.method public hidebysig virtual instance string
        ToString() cil managed
{
  // Code size       37 (0x25)
  .maxstack  3
  .locals init (string V_0)
  IL_0000:  ldstr      "({0}, {1}"
  IL_0005:  ldarg.0
  IL_0006:  ldfld      int32 Point::x
  IL_000b:  box        [mscorlib]System.Int32
  IL_0010:  ldarg.0
  IL_0011:  ldfld      int32 Point::y
  IL_0016:  box        [mscorlib]System.Int32
  IL_001b:  call       string [mscorlib]System.String::Format(string,
                                                              object,
                                                              object)
  IL_0020:  stloc.0
  IL_0021:  br.s       IL_0023
  IL_0023:  ldloc.0
  IL_0024:  ret
} // end of method Point::ToString

请各位高手指教。

转载于:https://www.cnblogs.com/gamix/archive/2005/04/12/136414.html