yield关键字的奇迹

dex*_*ter 6 c# enumeration yield yield-return

好吧,当我在构建一个自定义枚举器时,我注意到了这种与收益率有关的行为

说你有这样的事情:

  public class EnumeratorExample 
  {

        public static IEnumerable<int> GetSource(int startPoint) 
        {
                int[] values = new int[]{1,2,3,4,5,6,7};
                Contract.Invariant(startPoint < values.Length);
                bool keepSearching = true;
                int index = startPoint;

                while(keepSearching) 
                {
                      yield return values[index];
                      //The mind reels here
                      index ++ 
                      keepSearching = index < values.Length;
                }
        }

  } 
Run Code Online (Sandbox Code Playgroud)

在技​​术上从函数返回之后,是什么让编译器的底层可以执行索引++和while循环中的其余代码?

Mar*_*ers 9

编译器将代码重写为状态机.您编写的单个方法分为不同的部分.每次调用MoveNext(隐含或显式)时,状态都会提前,并执行正确的代码块.

如果您想了解更多详细信息,建议阅读: