invalid cast exception on int to double

我们两清 提交于 2019-12-03 14:48:45

问题


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

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

Why is LinqPad throwing a

InvalidCastException: Specified cast is not valid.

?


回答1:


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.



来源:https://stackoverflow.com/questions/12647068/invalid-cast-exception-on-int-to-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!