C# iterators are state machines internally. Every time you yield return
something, the place where you left off should be saved along with the state of local variables so that you could get back and continue from there.
To hold this state, C# compiler creates a class to hold local variables and the place it should continue from. It's not possible to have a ref
or out
value as a field in a class. Consequently, if you were allowed to declare a parameter as ref
or out
, there would be no way to keep the complete snapshot of the function at the time we had left off.
EDIT: Technically, not all methods that return IEnumerable<T>
are considered iterators. Just those that use yield
to produce a sequence directly are considered iterators. Therefore, while the splitting the iterator into two methods is a nice and common workaround, it doesn't contradict with what I just said. The outer method (that doesn't use yield
directly) is not considered an iterator.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…