C# yield return 流程理解

代码如下:  在Documents1方法中使用yield return之后, 下次在进入Documents1方法就是从上一次yield return部分执行

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace C数据结构与算法
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> docs1 = new List<string>();
            docs1.Add("1");
            docs1.Add("2");
            docs1.Add("3");
            docs1.Add("4");
            docs1.Add("5");
           
            foreach (string item in Documents1(docs1))
            {
                Console.WriteLine("获取值: " + item);
                Thread.Sleep(2000);
            }

            Console.ReadKey();
        }


        static IEnumerable Documents1(List<string> docs)
        {
            foreach (var item in docs)
            {
                if (item != "4")
                {
                    Console.WriteLine("返回值: " + item);
                    //yield return语句返回集合的一个元素,并移动到下一个元素上  
                    yield return item;
                    Console.WriteLine("用完值: " + item);
                }
                    
            }

            Console.Write(" {0} ", "循环完毕");
        }
    }
}

image

posted @ 2015-07-25 00:21  盘子脸  阅读(384)  评论(0编辑  收藏  举报