C# 迭代器与yield关键字

yield关键字在迭代器中,用于向枚举对象返回元素值或发出迭代结束信号。

迭代器能够在类或结构中支持foreach迭代,而不必实现IEnumerable接口。

创建迭代器最常用的方法是对IEnumerable接口实现GetEnumerator方法。

using System;
using System.Collections;
using System.Collections.Generic;

namespace DemoIterator1
{
    /// <summary>
    /// 包含迭代器的自定义集合类
    /// </summary>
    public class MyDocuments : IEnumerable
    {
        private List<string> docs = new List<string>();

        public void Add(string s)
        {
            docs.Add(s);
        }

        #region IEnumerable 成员

        public IEnumerator GetEnumerator()
        {
            foreach (string s in docs)
            {
                yield return s;
            }

        }

        #endregion/**/
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("从包含自定义迭代器的集合类中枚举元素\n");
            //初始化自定义集合
            MyDocuments document = new MyDocuments();
            document.Add("依莲");
            document.Add("玉珈");
            document.Add("徐长今");
            document.Add("宁雨昔");
            document.Add("安碧如");
            document.Add("洛凝");
            document.Add("萧玉若");

            //通过带有自定义迭代器的类枚举元素
            foreach (string s in document)
                Console.Write(string.Format(" {0} ", s));

            Console.WriteLine("\n**********************************************\n");
            Console.WriteLine("从自定义迭代器方法中枚举元素\n");

            List<string> docs = new List<string>();
            docs.Add("依莲");
            docs.Add("玉珈");
            docs.Add("徐长今");
            docs.Add("宁雨昔");
            docs.Add("安碧如");
            docs.Add("洛凝");
            docs.Add("萧玉若");

            //通过自定义迭代器方法中枚举元素
            foreach (string s in Documents(docs))
                Console.Write(string.Format(" {0} ",s));

            Console.ReadKey();
        }

        /// <summary>
        /// 迭代器方法
        /// </summary>
        static IEnumerable Documents(List<string> docs)
        {
            foreach (string s in docs)
            {
                yield return s;
            }
        }

    }
}

注:本文代码来自《LINQ入门及应用》!!!

原文地址:https://www.cnblogs.com/YuanSong/p/2620039.html