拆箱转换

本文详细介绍了C#中的装箱与拆箱概念,包括它们的定义、工作原理及如何在代码中实现。通过具体示例展示了正确的使用方式与不当操作可能导致的问题,并提供了异常处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 type
object box = i;       // Boxing
int 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值