装箱/拆箱和类型转换有什么区别? [英] What is the difference between boxing/unboxing and type casting?

查看:27
本文介绍了装箱/拆箱和类型转换有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

装箱/拆箱和类型转换有什么区别?

What is the difference between boxing/unboxing and type casting?

通常,这些术语似乎可以互换使用.

Often, the terms seem to be used interchangeably.

推荐答案

装箱是指将不可空值类型转换为引用类型或将值类型转换为它实现的某个接口(比如 intIComparable).此外,底层值类型到可为空类型的转换也是一种装箱转换.(警告:关于这个主题的大多数讨论都会忽略后两种类型的转换.)

Boxing refers to a conversion of a non-nullable-value type into a reference type or the conversion of a value type to some interface that it implements (say int to IComparable<int>). Further, the conversion of an underlying value type to a nullable type is also a boxing conversion. (Caveat: Most discussions of this subject will ignore the latter two types of conversions.)

例如

int i = 5;
object o = i;

i 转换为 object 类型的实例.

converts i to an instance of type object.

拆箱是指从 objectValueType 的实例到非空值类型的显式转换,接口类型到非空值类型的转换- 值类型(例如,IComparableint).此外,可空类型到基础类型的转换也是一种拆箱转换.(警告:关于这个主题的大多数讨论都会忽略后两种类型的转换.)

Unboxing refers to an explicit conversion from an instance of object or ValueType to a non-nullable-value type, the conversion of an interface type to a non-nullable-value type (e.g., IComparable<int> to int). Further, the conversion of a nullable type to the underlying type is also an unboxing conversion. (Caveat: Most discussion of this subject will ignore the latter two types of conversions.)

例如

object o = (int)5;
int i = (int)o;

o 中装箱的整数转换为int 类型的实例.

converts the integer boxed in o to an instance of type int.

类型转换是将表达式显式转换为给定类型.于是

A type cast is an explicit conversion of an expression to a given type. Thus

(type) expression

显式地将 expression 转换为 type 类型的对象.

explicitly converts expression to an object of type type.

这篇关于装箱/拆箱和类型转换有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆