装箱/拆箱和类型强制转换之间的区别是什么? [英] What is the difference between boxing/unboxing and type casting?

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

问题描述

装箱/拆箱和类型强制转换之间的区别是什么?

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

通常,术语似乎被可互换地使用。

Often, the terms seem to be used interchangeably.

推荐答案

拳击是指转换为非可空值类型为引用类型或值类型,它实现了一些接口的转换(比如< $ C C> INT $以 IComparable的&LT; INT&GT; )。此外,潜在的价值类型为可空类型的转换也是一个装箱转换。 (告诫:这个问题上的多数讨论将忽略后两种类型的转换)

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;

转换来类型的实例对象

拆箱指的是一个明确的转换,从对象值类型来一个非空的值类型的实例,接口类型为一个非可空值类型转换(例如, IComparable的&LT; INT&GT; INT )。此外,可空类型的基础类型的转换也是一个拆箱转换。 (告诫:这个问题上会忽略后两种类型的转换的大部分讨论)

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;

转换成键入 INT 的实例盒装 0 的整数。

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

一个类型转换是显式的前pression转换为给定类型。因此,

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

(type) expression

明确转换 EX pression 来类型的对象键入

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

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