IEnumerable.Cast() vs casting in IEnumerable.Select()

偶尔善良 提交于 2019-12-23 07:27:32

问题


Suppose I have an IEnumerable<int> and I want these to be converted into their ASCII-equivalent characters.

For a single integer, it would just be (char)i, so there's always collection.Select(i => (char)i), but I thought it would be a tad cleaner to use collection.Cast().

Can anyone explain why I get an InvalidCastException when I use collection.Cast<char>() but not with collection.Select(i => (char)i)?

Edit: Interestingly enough, when I call collection.OfType<char>() I get an empty set.


回答1:


The Cast<T> and OfType<T> methods only perform reference and unboxing conversions. So they can't convert one value type to another value type.

The methods operate on the non-generic IEnumerable interface, so they're essentially converting from IEnumerable<object> to IEnumerable<T>. So, the reason you can't use Cast<T> to convert from IEnumerable<int> to IEnumerable<char> is that same reason that you can't cast a boxed int to a char.

Essentially, Cast<char> in your example fails because the following fails:

object ascii = 65;
char ch = (char)ascii;   <- InvalidCastException

See Jon Skeet's excellent EduLinq post for more details.



来源:https://stackoverflow.com/questions/9866199/ienumerable-cast-vs-casting-in-ienumerable-select

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