为什么此转换无效? [英] Why does this conversion doesn't work?
本文介绍了为什么此转换无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码行为异常(至少对我来说):
following code behaves strange (at least for me):
int testValue = 1234;
this.ConversionTest( testValue );
private void ConversionTest( object value )
{
long val_1 = (long) (int) value; // works
long val_2 = (long) value; // InvalidCastException
}
我不明白为什么直接长不工作。
有人可以解释这个行为吗?
I don't understand why the direct (explicit) cast to long doesn't work. Can someone explain this behaviour?
感谢
推荐答案
ConversionTest
方法的值
参数类型为 object
;这意味着传递给方法的任何值类型 - 例如 int
- 将被加框。
The value
parameter of your ConversionTest
method is typed as object
; this means that any value types -- for example, int
-- passed to the method will be boxed.
装箱值只能取消装箱到完全相同的类型:
Boxed values can only be unboxed to exactly the same type:
- 当您执行
(long)
您首先将值解除到
int
(其原始类型)到
长
。 - 当<$ c $
int
到长
>,这是非法的。
- When you do
(long)(int)value
you're first unboxingvalue
to anint
(its original type) and then converting thatint
to along
. - When you do
(long)value
you're attempting to unbox the boxedint
to along
, which is illegal.
这篇关于为什么此转换无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文