use*_*783 5 c# ienumerable ienumerator iterator
使用yield return将方法变成迭代器。迭代器的返回类型必须是IEnumerable、IEnumerable<T>、IEnumerator或IEnumerator<T>。
我发现迭代器只能foreach在返回其中一种IEnumerable类型的情况下在循环中使用。考虑到这一限制,什么时候选择IEnumerator返回类型而不是才有意义IEnumerable?
老实说,很少见。我看到它以这种方式使用的唯一一次是当由于某种原因在GetEnumerator()方法中进行特殊处理时(在启动迭代器块机制之前),但仍然需要一个迭代器块来实际实现,即
public IEnumerator<T> GetEnumerator()
{
if (someScenario) return SomethingSpecialPerhapsEmptyArrayEnumerator();
if (anotherScenario) ThrowSomeException();
return DoTheThing();
}
private IEnumerator<T> DoTheThing()
{
// ... yield return
}
Run Code Online (Sandbox Code Playgroud)