问题
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