Why can't iterator methods take either 'ref' or 'out' parameters?

前端 未结 5 1317
鱼传尺愫
鱼传尺愫 2021-01-31 08:36

I tried this earlier today:

public interface IFoo
{
    IEnumerable GetItems_A( ref int somethingElse );
    IEnumerable GetItems_B( ref in         


        
5条回答
  •  孤城傲影
    2021-01-31 09:02

    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 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.

提交回复
热议问题