什么是.Cast过。选择什么好处? [英] What's the benefit of .Cast over .Select?
问题描述
我有隐式转换运营商类型最基本类型,并试图用 .Cast<串>()
这种类型,其失败的集合。正如我挖了进去,我注意到,通过铸造为
不使用隐性或显性的转换,只是将无法编译,所以我想这就是 .Cast
落下。所以这个失败
I have a type with implicit conversion operators to most base types and tried to use .Cast<string>()
on a collection of this type, which failed. As I dug into it, I noticed that casting via as
doesn't use implicit or explicit conversion and just won't compile, so I guess that's where .Cast
falls down. So this fails
var enumerable = source.Cast<string>();
但这个作品
but this works
var enumerable = source.Select(x => (string)x);
那么,什么是演员的好处?当然,这是一对夫妇更短的字符,但似乎有更多的限制。如果它可用于转换,有没有一些不是更紧凑语法其他利益?
So what's the benefit of Cast? Sure, it's a couple of characters shorter, but seems a lot more limited. If it can be used for conversion, is there some benefit other than the more compact syntax?
推荐答案
的演员
的好处来当你的收集只实现的IEnumerable
(即。没有通用版)。在这种情况下,铸造
通过转换成 TResult
所有元素转换,并返回的IEnumerable< TResult> ;
。这是非常方便的,因为所有其他LINQ扩展方法(包括选择
)只申报的IEnumerable< T>
。在代码中,它看起来是这样的:
Cast usage
The benefit of Cast
comes when your collection only implements IEnumerable
(ie. not the generic version). In this case, Cast
converts all elements to TResult
by casting, and returns IEnumerable<TResult>
. This is handy, because all the other LINQ extension methods (including Select
) is only declared for IEnumerable<T>
. In code, it looks like this:
IEnumerable source = // getting IEnumerable from somewhere
// Compile error, because Select is not defined for IEnumerable.
var results = source.Select(x => ((string)x).ToLower());
// This works, because Cast returns IEnumerable<string>
var results = source.Cast<string>().Select(x => x.ToLower());
铸造
和 OfType
是是为的IEnumerable
定义的只有两个LINQ扩展方法。 OfType
就像铸造
,但跳过那些类型不同元素 TResult
而不是抛出异常。
Cast
and OfType
are the only two LINQ extension methods that are defined for IEnumerable
. OfType
works like Cast
, but skips elements that are not of type TResult
instead of throwing an exception.
之所以你的隐式转换操作符的当您使用不工作铸造
很简单:铸造
的演员对象
到 TResult
- 和你的转换不是为对象
,只为你特定的类型。为演员
的实施是这样的:
The reason why your implicit conversion operator is not working when you use Cast
is simple: Cast
casts object
to TResult
- and your conversion is not defined for object
, only for your specific type. The implementation for Cast
is something like this:
foreach (object obj in source)
yield return (TResult) obj;
这铸的失败进行转换,对应基本的转换规则 - 由此所见例如:
This "failure" of cast to do the conversion corresponds to the basic conversion rules - as seen by this example:
YourType x = new YourType(); // assume YourType defines an implicit conversion to string
object o = x;
string bar = (string)x; // Works, the implicit operator is hit.
string foo = (string)o; // Fails, no implicit conversion between object and string
这篇关于什么是.Cast过。选择什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!