该函数仅调用一次,以返回
IEnumerator<T>; 之后,使用
MoveNext()方法和
Current属性来迭代结果:
foreach (Foo f in GetFoos()){ // Do stuff}在某种程度上等效于:
using (IEnumerator<Foo> iterator = GetFoos().GetEnumerator()){ while (iterator.MoveNext()) { Foo f = iterator.Current; // Do stuff }}请注意,迭代器放置在末尾-这对于从迭代器块释放资源特别重要,例如:
public IEnumerable<string> GetLines(string file){ using (TextReader reader = File.OpenText(file)) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } }}在上面的代码中,您确实希望在完成迭代后关闭文件,并且编译器
IDisposable巧妙地实现了该工作。



