收益回报与收益选择 [英] yield return versus return select
问题描述
哪些是优点/这两种方法的缺点?
Which are the advantages/drawbacks of both approaches?
return items.Select(item => DoSomething(item));
与
foreach(var item in items)
{
yield return DoSomething(item);
}
修改作为他们MSIL大致相当,哪一个你觉得更可读?
EDIT As they are MSIL roughly equivalent, which one you find more readable?
推荐答案
在收益率回报
技术使C#编译器生成的枚举器类幕后的同时,在选择
调用使用一个标准的枚举器类参数化的委托。在实践中,不应该有一大堆,两者之间的差异,可能比在选择
情况下的额外调用框架等,为代表。
The yield return
technique causes the C# compiler to generate an enumerator class "behind the scenes", while the Select
call uses a standard enumerator class parameterized with a delegate. In practice, there shouldn't be a whole lot of difference between the two, other than possibly an extra call frame in the Select
case, for the delegate.
有关它的价值,围绕包装的lambda 的DoSomething
是那种毫无意义的为好;只是通过一个委托直接。
For what it's worth, wrapping a lambda around DoSomething
is sort of pointless as well; just pass a delegate for it directly.
这篇关于收益回报与收益选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!