投射盒装值 [英] Casting a boxed value
本文介绍了投射盒装值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么不能将 int
投入到 double
?
object o = 12;
double d = (double)o;
抛出无效的投射异常。相反,它似乎必须首先被转换为 int
,然后到 double
。
That throw an invalid cast exception. Instead it seems it has to first be cast as an int
, and then on to double
.
object o = 12;
double d = (double)(int)o;
我相信简单的答案是因为这是拳击的工作原理,但我希望有人
I'm sure the simple answer is "because that's how boxing works" but I'm hoping someone might shed a bit of light here.
推荐答案
今天早些时候查看这个问题:为什么我收到InvalidCastException?
Check out this question from earlier today: Why am I getting InvalidCastException?
取消装箱操作只有在目标类型与被装箱的原始类型完全相同时才会成功,所以抛出异常。 John Leidegren提供的此链接详细说明。
这篇关于投射盒装值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文