为什么 (int)(object)10m 抛出“指定的强制转换无效"?例外? [英] Why does (int)(object)10m throw "Specified cast is not valid" exception?

查看:12
本文介绍了为什么 (int)(object)10m 抛出“指定的强制转换无效"?例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个显式转换会抛出指定的转换无效.异常?

Why this explicit cast does throw Specified cast is not valid. exception ?

decimal d = 10m;
object o = d;
int x = (int)o;

但这有效:

int x = (int)(decimal)o;

推荐答案

装箱的值只能取消装箱到完全相同类型的变量.这个看似奇怪的限制是一个非常重要的速度优化,它使 .NET 1.x 在泛型可用之前变得可行.您可以在这个答案中阅读更多相关信息.

A boxed value can only be unboxed to a variable of the exact same type. This seemingly odd restriction is a very important speed optimization that made .NET 1.x feasible before generics were available. You can read more about it in this answer.

您不想跳过多重转换,简单的值类型实现了 IConvertible 接口.您使用 Convert 类调用的:

You don't want to jump through the multiple cast hoop, simple value types implement the IConvertible interface. Which you invoke by using the Convert class:

        object o = 12m;
        int ix = Convert.ToInt32(o);

这篇关于为什么 (int)(object)10m 抛出“指定的强制转换无效"?例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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