开发者

Casting IEnumerable<int> to IEnumerable<long> fails [duplicate]

开发者 https://www.devze.com 2023-01-30 23:06 出处:网络
This question already has answers he开发者_StackOverflow社区re: Closed 12 years ago. Possible Duplicate:
This question already has answers he开发者_StackOverflow社区re: Closed 12 years ago.

Possible Duplicate:

Puzzling Enumerable.Cast InvalidCastException

Why does

List<long> numbers = Enumerable.Range(1, 9999).Cast<long>().ToList();

fail with an InvalidCastException?


See this answer: Puzzling Enumerable.Cast InvalidCastException

In summary, Cast() works on the non-generic IEnumerable, which boxes each int as an Object. So, when the Cast is called it can only treat the elements as being of type Object, which cannot be cast to long.

The solution is to use Select to perform an explicit cast:

var numbers = Enumerable.Range(1,9999).Select(i=>(long)i).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号