11.3 Boxing and unboxing

本文围绕C#的装箱和拆箱操作展开。装箱允许值类型隐式转换为object类型或接口类型,需分配对象实例并复制值;拆箱则是从object类型显式转换为值类型,要先检查对象是否为对应值类型的装箱值,再复制值。操作不当会抛出异常。

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

11.3 Boxing and unboxing
The concept of boxing and unboxing is central to C#.s type system. It
provides a bridge between value-types
and reference-types by permitting any value of a value-type to be converted
to and from type object.
Boxing and unboxing enables a unified view of the type system wherein a
value of any type can ultimately
be treated as an object.
11.3.1 Boxing conversions
A boxing conversion permits any value-type to be implicitly converted to
the type object or to any
interface-type implemented by the value-type. Boxing a value of a
value-type consists of allocating an object
instance and copying the value-type value into that instance.
The actual process of boxing a value of a value-type is best explained by
imagining the existence of a boxing
class for that type. [Example: For any value-type T, the boxing class
behaves as if it were declared as
follows:
sealed class T_Box
{
T value;
public T_Box(T t) {
value = t;
}
}
Boxing of a value v of type T now consists of executing the expression new
T_Box(v), and returning the
resulting instance as a value of type object. Thus, the statements
int i = 123;
object box = i;
conceptually correspond to
int i = 123;
object box = new int_Box(i);
end example]
Chapter 11 Types
97
Boxing classes like T_Box and int_Box above don.t actually exist and the
dynamic type of a boxed value
isn.t actually a class type. Instead, a boxed value of type T has the
dynamic type T, and a dynamic type
check using the is operator can simply reference type T. [Example: For
example,
int i = 123;
object box = i;
if (box is int) {
Console.Write("Box contains an int");
}
will output the string .Box contains an int. on the console. end example]
A boxing conversion implies making a copy of the value being boxed. This is
different from a conversion of
a reference-type to type object, in which the value continues to reference
the same instance and simply is
regarded as the less derived type object. [Example: For example, given the
declaration
struct Point
{
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
the following statements
Point p = new Point(10, 10);
object box = p;
p.x = 20;
Console.Write(((Point)box).x);
will output the value 10 on the console because the implicit boxing
operation that occurs in the assignment
of p to box causes the value of p to be copied. Had Point been declared a
class instead, the value 20
would be output because p and box would reference the same instance. end
example]
11.3.2 Unboxing conversions
An unboxing conversion permits an explicit conversion from type object to
any value-type or from any
interface-type to any value-type that implements the interface-type. An
unboxing operation consists of first
checking that the object instance is a boxed value of the given value-type,
and then copying the value out of
the instance.
Referring to the imaginary boxing class described in the previous section,
an unboxing conversion of an
object box to a value-type T consists of executing the expression
((T_Box)box).value. [Example: Thus,
the statements
object box = 123;
int i = (int)box;
conceptually correspond to
object box = new int_Box(123);
int i = ((int_Box)box).value;
end example]
For an unboxing conversion to a given value-type to succeed at run-time,
the value of the source operand
must be a reference to an object that was previously created by boxing a
value of that value-type. If the
source operand is null a System.NullReferenceException is thrown. If the
source operand is a
reference to an incompatible object, a System.InvalidCastException is
thrown.
### Java中的装箱与拆箱 Java 提供了一种自动转换机制,称为 **装箱**(Boxing)和 **拆箱**(Unboxing)。这种机制允许在原始数据类型(如 `int`, `double` 等)与其对应的包装类(如 `Integer`, `Double` 等)之间进行无缝转换。这一功能自 Java 5 引入以来极大地简化了开发者的编码过程[^1]。 #### 装箱(Boxing) 装箱是指将原始数据类型自动转换为其对应的包装类实例的过程。例如,当我们将一个 `int` 值赋给一个 `Integer` 对象时,JVM 会自动创建一个新的 `Integer` 实例来保存这个值。 ```java // Example of autoboxing Integer boxedValue = 42; // Automatically converts int to Integer object ``` 在此代码片段中,整数值 `42` 被隐式地转换成了 `Integer` 类型的对象[^1]。 #### 拆箱(Unboxing) 相反,拆箱则是指将包装类实例自动转换回其对应的原始数据类型的操作。例如,当我们从一个 `Integer` 对象中提取出它的基础 `int` 值时,即发生了拆箱行为。 ```java // Example of auto-unboxing int unboxedValue = boxedValue; // Automatically extracts int value from Integer object ``` 这里展示了如何将前面定义的 `Integer` 变量重新转回成普通的 `int` 数据类型[^1]。 需要注意的是虽然这些操作看起来很方便,但在某些情况下可能会引发性能问题或者 NullPointerExceptions 如果尝试对 null 引用执行拆箱动作的话[^3]。 --- ### 注意事项 尽管装箱/拆箱提供了便利性,但也存在一些潜在风险: - 性能开销:频繁地进行装箱或拆箱可能会影响应用程序的整体效率。 - NullPointer Exceptions:如果试图拆箱一个null引用,则会导致运行时错误。 因此,在实际项目开发过程中应当谨慎使用此类特性,并充分理解其中的工作原理以便更好地控制程序的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值