为什么(INT)(对象)10米掷"指定的转换是无效的"例外? [英] Why does (int)(object)10m throw "Specified cast is not valid" exception?

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

问题描述

为什么这样明确的转换并抛出指定的转换是无效的。例外呢?

 十进制D =10米;
对象o = D;
INT X =(INT)O;

但这个作品:

  INT X =(INT)(十进制)O;


解决方案

一个装箱值只能是拆箱到同一个类型的变量。这个看似奇怪的限制是一个非常重要的速度优化,使得仿制药是可用之前.NET 1.x中是可行的。您可以阅读<一个更多一点href=\"http://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types/3076525#3076525\">this回答。

您不必通过多种投圈跳,简单的值类型实现IConvertible接口。您使用Convert类调用:

 对象o =12米;
        INT九= Convert.ToInt32(O);

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

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

But this works:

int x = (int)(decimal)o;

解决方案

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.

You don't have 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)(对象)10米掷&QUOT;指定的转换是无效的&QUOT;例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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