试图投装箱的int到byte [英] Trying to cast a boxed int to byte
问题描述
code来说明:
int i = 5;
object obj = i;
byte b = (byte)obj; // X
在运行,这会产生一个System.InvalidCastException(指定的转换无效)于行X。做一个双投作品:
When run, this generates a System.InvalidCastException ("Specified cast is not valid") at line "X". Doing a double cast works :
byte b = (byte)(int)obj;
我本来以为你应该能够施展装箱的int(如果它在范围0..255的值),以一个字节。任何人都可以阐明这个任何光线?
I would have thought that you ought to be able to cast a boxed int (if it has a value in the range 0..255) to a byte. Can anyone shed any light on this ?
(这是.NET 2.0,如果该事项)。
(This is in .net 2.0, in case that matters).
推荐答案
在你所看到的行为偏差在<一的区别href="http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/re$p$psentation-and-identity.aspx">identity并重新presentation 。
The difference in behaviour you're seeing is the difference between identity and representation.
拆箱是的的身份的演员阵容,和再presentation- preserving 的操作。铸造一个 INT
到字节
,但是,的再presentation变化的(因为是precision潜在损失)
Unboxing is an identity cast, and a representation-preserving operation. Casting an int
to a byte
, however, is representation-changing (since there is a potential loss of precision).
您获得 InvalidCastException的
当您尝试拆箱 INT
为字节
因为装箱值的的身份不是字节
,它是一个 INT
。当你写字节B =(字节)目标文件
,你说的是运行时,的我知道这里面有什么了是 字节
的,但你真正的意思是说,我认为这里面有什么了可转换到字节
的。
You get an InvalidCastException
when you try to unbox the int
as a byte
because the identity of the boxed value is not a byte
, it is an int
. When you write byte b = (byte)obj
, you are telling the runtime, I know that what's in there is a byte
, but what you really mean to say is, I think that what's in there can be converted to a byte
.
为了使后者的说法,你首先要声明的的身份的对象,这是一个 INT
。那时,也只有这样你才能做出重新presentation变化转化为字节
。
In order to make the latter statement, you first have to declare the identity of the object, which is an int
. Then and only then can you make a representation-changing conversion to byte
.
请注意,这适用即使目标类型为大 - 即一个的Int64
。 所有的显式转换为其目标类型不在源类型的继承树被认为是重新presentation变化。由于所有类型从 System.Object的
导出,顾名思义拆箱不能改变重presentation。
Note that this applies even if the target type is "larger" - i.e. an Int64
. All explicit conversions for which the destination type is not in the inheritance tree of the source type are considered to be representation-changing. And since all types derive from System.Object
, unboxing by definition cannot change the representation.
这篇关于试图投装箱的int到byte的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!