IEnumerable.Cast<> [英] IEnumerable.Cast<>

查看:123
本文介绍了IEnumerable.Cast<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我能一个整数值隐式转换为双,如:

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

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

我为什么不能做到这一点:

Why can I not do this:

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

我收到一个指定强制转换无效 InvalidCastException的例外。

在做相反(从双铸造为int)在同样的错误结果。

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

我在做什么错了?

推荐答案

好了,你有演员不正确的期待,这一切 - 它的意思处理装箱/拆箱,参考和身份的转换,而这一切。这是不幸的文件不明确的,因为它可能是:(

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 :(

该解决方案是使用选择

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

这篇关于IEnumerable.Cast&LT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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