working pattern of yield return

前端 未结 4 1425
一整个雨季
一整个雨季 2021-02-07 22:43

When i have a code block

static void Main()
{

  foreach (int i in YieldDemo.SupplyIntegers())
  {
    Console.WriteLine(\"{0} is consumed by foreach iteration\         


        
4条回答
  •  余生分开走
    2021-02-07 23:11

    Simply put, iterator blocks (or methods with yield statements, if you may) are transformed by the compiler into a compiler-generated class. This class implements IEnumerator and the yield statement is transformed into a 'state' for that class.

    For instance, this:

    yield return 1;
    yield return 2;
    yield return 3;
    

    might get transformed into something similar to:

    switch (state)
    {
        case 0: goto LABEL_A;
        case 1: goto LABEL_B;
        case 2: goto LABEL_C;
    }
    LABEL_A:
        return 1;
    LABEL_B:
        return 2;
    LABEL_C:
        return 3;
    

    Iterator blocks are can be seen as abstracted state machines. This code will be invoked by IEnumerator's methods.

提交回复
热议问题