何时发生boxing,到MSDN上查了一下,如下
From any value-type (including any enum-type) to the type object. 
From any value-type (including any enum-type) to the type System.ValueType. 
From any value-type to any interface-type implemented by the value-type. 
From any enum-type to the type System.Enum. 
第三句大家如何理解啊?

解决方案 »

  1.   

    假设一个value type,
    struct Point
    {
       public int x, y;
       public Point(int x, int y) {
          this.x = x;
          this.y = y;
       }
    }Point p = new Point(10, 10);
    object o=p;
    //这里肯定发生了boxing,因为符合第一条"From any value-type (including any enum-type) to the type object."
    ReferenceType rt=p;
    MSDN中明确写明rt必须是interface-type implemented by the value-type,但怎样的rt才能被称为interface-type implemented by the value-type呢?请指教!
      

  2.   

    这段代码:
    int n = 123;
    IComparable i = n;
    Console.WriteLine(i.CompareTo(122));
    int类型实现了IComparable接口,所以第二句是正确的,但这里的n会发生装箱操作,就是“From any value-type(这里是int类型) to any interface-type(这里是IComparable类型) implemented by the value-type. ”所说的情形。最后一句中的i.CompareTo(122)也发生了装箱,是第一条中说的情形。
      

  3.   

    就是说你的值类型继承了一个接口类型;可以通过boxing把这个值类型装到接口类型中去。类似于把子类型转换为父类型了。我觉得这没什么难理解的呀。
      

  4.   

    请问fancyf(凡瑞),如果将代码改为以下样式,还会发生boxing吗
    int n = 123;
    ReClassIComparable i = n;public class ReClassIcomparable:IComparable
    {}
      

  5.   

    int n = 123;
    ReClassIComparable i = n;public class ReClassIcomparable:IComparable
    {}
    这里的
    ReClassIComparable i = n;
    是不允许的,ReClassIcomparable与int没有继承关系,无法转换
      

  6.   

    结贴总结,不对请大家指教
    boxing与unboxing是发生在families class中的一种操作,当等号两边的类型不是同一类型的时候(reference type或value type),我们需要boxing与unboxing来改变对象在内存中存在的位置(stack或heap),boxing是隐式的进行(你会发现=右边的操作数families class中总是derived types),unboxing需要显式的执行(你会发现=左边的操作数在families class中总是derived types).
    eg:
    BOXING
    int i=1;
    IComparable i = n;//int实现IComparableint j=2;
    object o=j;//object是任何familes class中的基类
    if (o is object)
    {.....}Unboxingobject box = 123;
    if (box is int)
      {int i = (int)box;}//object->int.
      

  7.   

    unboxing发生的时机,from MSDN
    From the type object to any value-type (including any enum-type). 
    From the type System.ValueType to any value-type (including any enum-type). 
    From any interface-type to any value-type that implements the interface-type. 
    From the type System.Enum to any enum-type. Boxing发生的时机,from MSDN
    From any value-type (including any enum-type) to the type object. 
    From any value-type (including any enum-type) to the type System.ValueType. 
    From any value-type to any interface-type implemented by the value-type. 
    From any enum-type to the type System.Enum. 
      

  8.   

    谢谢,fancyf(凡瑞),mituzhishi(慎独)!