working pattern of yield return

前端 未结 4 1424
一整个雨季
一整个雨季 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 22:56

    in short, (while yr waiting for marc's long-hand version) when the compiler sees yield statements, behind the scenes it builds a new instance of a custom class for you that implements an interface called IEnumerator, which has methods Current(), and MoveNext(), and keeps track of where you are currently in the iteration process... In the case above as your example, it would also keep track of the values in the list to be enumerated through.

提交回复
热议问题