invalid cast exception on int to double

笑着哭i 提交于 2019-12-03 05:31:11

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.

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