int上无效的强制转换异常为double [英] invalid cast exception on int to double

查看:115
本文介绍了int上无效的强制转换异常为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我疯了,但我认为这是有效的演员表:

Maybe I'm crazy, but I thought this was a valid cast:

(new int[]{1,2,3,4,5}).Cast<double>()

LinqPad为什么要扔一个

Why is LinqPad throwing a

InvalidCastException:指定的转换无效.

InvalidCastException: Specified cast is not valid.

?

推荐答案

C#允许从int直接转换为double,但不能从int转换为object转换为double.

C# allows a conversion from int directly to double, but not from int to object to double.

int i = 1;
object o = i;
double d1 = (double)i; // okay
double d2 = (double)o; // error

Enumerable.Cast扩展方法的行为类似于后者.它不会将值转换为其他类型,而是断言值已经是预期类型,如果不是,则会引发异常.

The Enumerable.Cast extension method behaves like the latter. It does not convert values to a different type, it asserts that values are already of the expected type and throws an exception if they aren't.

您可以尝试使用(new int[]{1,2,3,4,5}).Select(i => (double)i)来获取价值转换行为.

You could try (new int[]{1,2,3,4,5}).Select(i => (double)i) instead to get the value-converting behaviour.

这篇关于int上无效的强制转换异常为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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