在前面提到了值类型和引用类型。这里就来和大家一起了解一下,他们互相转换的过程装箱(boxing)、拆箱(unboxing)。
由于C#中所有的数据类型都是由基类System.Object继承而来的,所以值类型和引用类型的值可以通过显式(或隐式)操作相互转换,而这转换过程也就是装箱(boxing)和拆箱(unboxing)过程。
装箱 是值类型到装换成引用类型时发生。
拆箱 是引用类型示转换为值类型时发生。
int i = 10; object obj = (object)i; //装箱,值会被拷贝到堆(heap)中 i = (int)obj; //拆箱,值会从堆(heap)拷贝到栈(stack)中