invalid cast exception on int to double

前端 未结 1 812
醉话见心
醉话见心 2021-02-06 23:41

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

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

Why is LinqPad throwing a

相关标签:
1条回答
  • 2021-02-07 00:36

    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
    

    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.

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

    0 讨论(0)
提交回复
热议问题