将0.0强制转换为两倍有什么问题? [英] What's wrong with casting 0.0 to double?

查看:115
本文介绍了将0.0强制转换为两倍有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将0.0转换为double时,我有 InvalidCastException ,为什么会这样?代替(float)value 很好。

I have InvalidCastException when I try to cast 0.0 to double, why is that so? It's fine when I do (float)value instead.

推荐答案

通常,当您输入值时键入对象(称为 boxing ),您需要将其 unbox 完全匹配 值类型。您不能将其转换为其他类型。这就是这里发生的情况。

In general, when you put a value type into an object (called boxing) you need to unbox it to the exact same value type. You cannot do a conversion to another type instead. This is what happens here.

如果您真的要转换对象,请先 将其拆箱。假设您的原始值是 float ,然后再将其装在对象中:

If you really want to convert the object, you first need to unbox it. Say your original value was a float before you boxed it in an object:

double d = (double) (float) value;

或使用其他人建议的方法,该方法使用转换。这样做的好处是不必知道原始类型。

Or use the method proposed by others, which uses Convert. This has the advantage that the original type doesn’t have to be known.

这篇关于将0.0强制转换为两倍有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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