在任何情况下,当出现以下情况时:
public IEnumerable<Foo> Foobar (Bar bar)
{
List<Foo> result = new List<Foo>()
foreach(var Qux in bar.QuxSource)
{
Foo item;
... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
result.Add(item);
... //The aforementioned inticate proceduce continues. Possiblily adding more items to result
}
return result;
}
优于:
public IEnumerable<Foo> Foobar (Bar bar)
{
foreach(var Qux in bar.QuxSource)
{
Foo item;
... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
yield return item;
... //The aforementioned inticate proceduce continues. Possiblily yielding more items
}
}
我的意思是后者显然很棒。 凭借延迟操作的荣耀,如果我只使用 Foobar(someBar).First(),它不必生成所有返回的项目。
我看到前者被大量使用,尤其是经验丰富的编码人员。 (我猜他们不了解现代 C# 中的列表推导)。 那么在某些情况下前一种模式是否更好呢? (仅查看库代码,以重用为目标) 我在想也许能够生产这些元素取决于某些外部资源,例如打开文件。 foreach 的用例是什么? 我猜是这样的
最佳答案
您的示例用例是正确的,但更一般地说,您可能希望采用前一种模式,如果:
- 源使用稀缺资源,您需要保证枚举器将被处置(如果您要在后一种方法中开始枚举并在中间停止而不处置枚举器,它将保持打开状态)里>
- 应尽快枚举来源
- 您必须保证评估整个源代码
关于c# - IEnumerable 理解与返回集合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013461/