Using yield in C#

前端 未结 4 739
粉色の甜心
粉色の甜心 2021-02-02 11:09

I have a vague understanding of the yield keyword in c#, but I haven\'t yet seen the need to use it in my code. This probably comes from a lack of understanding of

4条回答
  •  野的像风
    2021-02-02 12:02

    Yield is used in enumerators. The C# compiler automatically pauses execution of your enumeration loop and returns the current value to the caller.

    IEnumerable GetIntegers(int max) {
        for(int i = 1; i <= max) {
             yield return i; // Return current value to the caller
        }
    }
    

    -- or (more clunky) --

    IEnumerable GetIntegers(int max) {
        int count = 0;
        while(true) {
             if(count >= max) yield break; // Terminate enumeration
    
             count++;
             yield return count; // Return current value to the caller
        }
    }
    

    More details on MSDN.

提交回复
热议问题