拆箱转换
来源:互联网 发布:湖南卫视直播软件 编辑:程序博客网 时间:2024/06/02 15:37
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
- Checking the object instance to make sure it is a boxed value of the given value type.
- Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123; // A value typeobject box = i; // Boxingint j = (int)box; // Unboxing
The following figure demonstrates the result of the preceding statements.
Unboxing Conversion
For an unboxing conversion to a given value type to succeed at run time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value type. If the source argument is null or a reference to an incompatible object, an InvalidCastException is thrown.
Example
The following example demonstrates a case of invalid unboxing, of how incorrect unboxing leads to InvalidCastException. By using try and catch, an error message is displayed when the error occurs.
using System;public class UnboxingTest { public static void Main() { int intI = 123; // Boxing object o = intI; // Reference to incompatible object produces InvalidCastException try { int intJ = (short) o; Console.WriteLine("Unboxing OK."); } catch (InvalidCastException e) { Console.WriteLine("{0} Error: Incorrect unboxing.",e); } }}
Output
System.InvalidCastException at UnboxingTest.Main() Error: Incorrect unboxing.
If you change the statement:
int intJ = (short) o;
to:
int intJ = (int) o;
the conversion will be performed, and you will get the output Unboxing OK.
See Also
Boxing and Unboxing | Boxing Conversion
- 拆箱转换
- C#的拆箱转换
- java基本语法-装箱转换和拆箱转换
- C# 装箱和拆箱转换
- 装箱和拆箱数据类型转换
- 装箱和拆箱 VS 显示转换和隐式转换
- C#学习日记18----装箱(boxing)转换与拆箱(unboxing)转换
- C#,数据类型转换,装箱与拆箱概念,数据类型转换方法
- 转换
- 转换
- 转换
- 转换
- 转换
- 转换
- 转换
- 转换
- 转换
- 转换
- java 协变性和兼容性
- QT 软件键盘及动态属性
- mysql 中文字符集
- 检查是否存在SD卡
- AsyncTask的优化
- 拆箱转换
- 测试领域的学习和发展(我们都是温水的青蛙)
- 动态电压与频率调节在降低功耗中的作用
- [Leetcode]Valid Sudoku
- ASP.NET实现文件的上传和下载
- ORA-01722 无效数字的处理
- Highcharts--(3)x轴数据过多设置滚动条
- JSP学习
- hdu5108Revenge of Fibonacci