是否有过一个理由返回一个IEnumerable时,不使用“收益回报”? [英] Is there ever a reason to not use 'yield return' when returning an IEnumerable?
问题描述
简单的例子 - 你有一个方法或返回一个IEnumerable属性,主叫方被遍历,在foreach()循环。如果你的总是的使用您的IEnumerable的方法收益率回报呢?是否有过一个理由不?虽然我明白,它可能并不总是必要的,甚至是更好(也许是例如一个非常小集合),是有过一个理由来主动避免这样做?
Simple example - you have a method or a property that returns an IEnumerable and the caller is iterating over that in a foreach() loop. Should you always be using 'yield return' in your IEnumerable method? Is there ever a reason not to? While I understand that it may not always be necessary to, or even "better" (maybe it's a very small collection for example), is there ever a reason to actively avoid doing this?
中的代码,让我想到了,这是我写的非常相似,在这个线程接受的答案的函数的位 - 的 http://stackoverflow.com/questions/1847580/how-do-i-loop-through-a-date-range
The bit of code that got me thinking about this was a function I wrote very similar to the accepted answer in this thread - http://stackoverflow.com/questions/1847580/how-do-i-loop-through-a-date-range
推荐答案
迭代器块来执行一个活的评价每次都重复一次。
不过,有时候你想要的行为是结果是一个快照在某个时间点。在这种情况下,你可能不希望使用收益回报率
,而是返回一个列表与LT;>
或设置
,或其他一些持久化集合来代替。
Sometimes, however, the behavior you want is for the results to be a "snapshot" at a point in time. In these cases you probably don't want to use yield return
, but instead return a List<>
or Set
, or some other persistent collection instead.
这也是不需要使用收益回报
如果你正在处理的查询对象直接。这往往是与LINQ查询的情况下 - 这是更好地只返回的IEnumerable<>
从查询,而不是迭代和收益回报率
ING导致自己。例如:
It's also unnecessary to use yield return
if you're dealing with query objects directly. This is often the case with LINQ queries - it's better to just return the IEnumerable<>
from the query rather than iterating and yield return
ing results yourself. For example:
var result = from obj in someCollection
where obj.Value < someValue
select new { obj.Name, obj.Value };
foreach( var item in result )
yield return item; // THIS IS UNNECESSARY....
// just return {result} instead...
这篇关于是否有过一个理由返回一个IEnumerable时,不使用“收益回报”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!