What is the yield keyword used for in C#?

后端 未结 17 2016
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:26

In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:

IEnumerable FilteredList()
{
         


        
      
      
      
17条回答
  •  萌比男神i
    2020-11-22 05:54

    yield return is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the yield statement.

    Let us try to understand this with an example. In this example, corresponding to each line I have mentioned the order in which execution flows.

    static void Main(string[] args)
    {
        foreach (int fib in Fibs(6))//1, 5
        {
            Console.WriteLine(fib + " ");//4, 10
        }            
    }
    
    static IEnumerable Fibs(int fibCount)
    {
        for (int i = 0, prevFib = 0, currFib = 1; i < fibCount; i++)//2
        {
            yield return prevFib;//3, 9
            int newFib = prevFib + currFib;//6
            prevFib = currFib;//7
            currFib = newFib;//8
        }
    }
    

    Also, the state is maintained for each enumeration. Suppose, I have another call to Fibs() method then the state will be reset for it.

提交回复
热议问题