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

查看:22
本文介绍了为什么 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.

做相反的事情(从 double 到 int 的转换)会导致同样的错误.

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天全站免登陆