yield 一个很有趣的关键字

  在偶然的机会下发现了这个关键字yield,它的作用是在一个循环体(例如:foreach,for)内部 与return 一起做输出.要注意的是yield return 所在函数的返回值为IEnumerable接口类型

 下面实现的是从一堆数据中找出大于特定数字的结果集。

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] inputList = new int[5] { 2, 3, 4, 5, 6 };
            foreach (int item in GetTheHigherList(inputList,3))
            {
                Console.WriteLine(item.ToString());
            }
           Console.Read();
        }


        public static IEnumerable GetTheHigherList(int[] inputList,int lowerInt)
        {
            foreach (int item in inputList)
            {
                if (item > lowerInt)
                {
                    yield return item;
                }
            }
        }
    }
}

输出结果是:

4

5

6

posted @ 2011-07-06 14:13  修行  Views(182)  Comments(0)    收藏  举报