何时发生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.
第三句大家如何理解啊?
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.
第三句大家如何理解啊?
解决方案 »
- c# 资源文件的问题
- Oracle9中Date字段的读取问题?在c#或Asp.Net中如何读出??
- 如何使datagrid的某个数据列成为可编辑列?
- 从sql2005 导出image 格式的数据表 怎么把它插入到excel中
- 谁帮我看看这里出了什么问题,100分啊,够再给100分,请大侠帮帮俺!
- 谁能给我讲讲怎么给程序换肤,用IrisSkin2.dll控件
- ADO.net提升数据库事务隔离级别的方式有几种?
- IsPostBack与“未将对象引用设置到对象的实例”有何关系?各位给个说法
- 如何判断一个路径是否合法
- StreamReader读入的内容为何不对?
- 如何捕获异常详细信息: System.Net.WebException: 远程服务器返回错误: (404) 未找到
- 打包时,如何处理COM组件(excel),制作安装文件时出错:“可能具有不能自动确定的依赖项”,如何处理
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呢?请指教!
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)也发生了装箱,是第一条中说的情形。
int n = 123;
ReClassIComparable i = n;public class ReClassIcomparable:IComparable
{}
ReClassIComparable i = n;public class ReClassIcomparable:IComparable
{}
这里的
ReClassIComparable i = n;
是不允许的,ReClassIcomparable与int没有继承关系,无法转换
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.
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.