IEnumerable.Cast()VS在IEnumerable.Select铸造() [英] IEnumerable.Cast() vs casting in IEnumerable.Select()

查看:125
本文介绍了IEnumerable.Cast()VS在IEnumerable.Select铸造()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个的IEnumerable< INT方式> ,我想这些将被转换成它们的ASCII等效字符

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

有关一个整数,这纯粹是(char)的I ,所以总有 collection.Select(I =>(炭)我),但我认为这将是一点点清洁剂使用 collection.Cast()

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().

任何人都可以解释为什么我得到一个 InvalidCastException的当我使用 collection.Cast<烧焦>()但与 collection.Select(I =>(char)的我)

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

编辑:有趣的是,当我打电话 collection.OfType< char的方式>()我得到一个空集

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

推荐答案

演员LT; T> OfType< T> 方法只能执行基准和拆箱转换。因此,他们可以在一个值类型不能转换为其他类型的值。

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.

方法对非通用 IEnumerable的操作接口,所以他们基本上是从的IEnumerable<对象> 到的IEnumerable< T> 。因此,其原因不能使用演员LT; T> 转换IEnumerable的< INT> 的IEnumerable<焦炭> 是,你不能投了盒装 INT 字符

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.

从本质上讲,演员LT;焦炭> 在你的榜样,因为下面的失败,失败:

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

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

请参阅乔恩斯基特的出色的 EduLinq帖子了解更多详情。

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

这篇关于IEnumerable.Cast()VS在IEnumerable.Select铸造()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆