收益回报与收益选择 [英] yield return versus return select

查看:155
本文介绍了收益回报与收益选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪些是优点/这两种方法的缺点?

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屋!

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