为什么Enumerable.Cast引发InvalidCastException? [英] Why Enumerable.Cast raises an InvalidCastException?

查看:63
本文介绍了为什么Enumerable.Cast引发InvalidCastException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我可以将整数值隐式转换为双精度值,例如:

If I can implicitly cast an integer value to a double, like:

int a = 4;    
double b = a;
// now b holds 4.0

为什么我不能这样做:

int[] intNumbers = {10, 6, 1, 9};    
double[] doubleNumbers2 = intNumbers.Cast<double>().ToArray();

我收到指定的转换无效 InvalidCastException 异常。

I get a "Specified cast is not valid" InvalidCastException exception.

相反(从双精度转换为整数)会导致相同的错误。

Doing the opposite (casting from double to int) results in the same error.

我在做什么错了?

推荐答案

好吧,您对 Cast ,仅此而已-它的目的是处理装箱/拆箱,参考和身份转换,仅此而已。不幸的是,文档不够清晰:(

Well, you have incorrect expectations of Cast, that's all - it's meant to deal with boxing/unboxing, reference and identity conversions, and that's all. It's unfortunate that the documentation isn't as clear as it might be :(

解决方案是使用 Select

doubleNumbers2 = intNumbers.Select(x => (double) x).ToArray();

这篇关于为什么Enumerable.Cast引发InvalidCastException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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