Why Enumerable.Cast raises an InvalidCastException?

前端 未结 2 925
名媛妹妹
名媛妹妹 2020-11-27 06:49

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:

2条回答
  •  庸人自扰
    2020-11-27 07:16

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

    The solution is to use Select:

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

提交回复
热议问题