What does “yield break;” do in C#?

后端 未结 8 1951
南方客
南方客 2020-11-28 01:04

I have seen this syntax in MSDN: yield break, but I don\'t know what it does. Does anyone know?

8条回答
  •  攒了一身酷
    2020-11-28 01:20

    The yield break statement causes the enumeration to stop. In effect, yield break completes the enumeration without returning any additional items.

    Consider that there are actually two ways that an iterator method could stop iterating. In one case, the logic of the method could naturally exit the method after returning all the items. Here is an example:

    IEnumerable FindPrimes(uint startAt, uint maxCount)
    {
        for (var i = 0UL; i < maxCount; i++)
        {
            startAt = NextPrime(startAt);
            yield return startAt;
        }
    
        Debug.WriteLine("All the primes were found.");
    }
    

    In the above example, the iterator method will naturally stop executing once maxCount primes have been found.

    The yield break statement is another way for the iterator to cease enumerating. It is a way to break out of the enumeration early. Here is the same method as above. This time, the method has a limit on the amount of time that the method can execute.

    IEnumerable FindPrimes(uint startAt, uint maxCount, int maxMinutes)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        for (var i = 0UL; i < maxCount; i++)
        {
            startAt = NextPrime(startAt);
            yield return startAt;
    
            if (sw.Elapsed.TotalMinutes > maxMinutes)
                yield break;
        }
    
        Debug.WriteLine("All the primes were found.");
    }
    

    Notice the call to yield break. In effect, it is exiting the enumeration early.

    Notice too that the yield break works differently than just a plain break. In the above example, yield break exits the method without making the call to Debug.WriteLine(..).

提交回复
热议问题