C#基础--迭代器初识

先记住一句话:foreach语句是枚举器(enumerator)的消费者,而迭代器(iterator)是枚举器的产生者。

然后是两个单词的翻译 enumerator(枚举器) enumerable(可枚举类型)

下面举个例子:

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

namespace ConsoleApp1
{
    
    class Program
    {
        static IEnumerable<string> AddAB(int Count)
        {
            string str = "h";
            for (int i = 0 ; i < Count; i++)
            {
                yield return str;
                str += "a";
            }
            Console.WriteLine("");
            for (int i = 0 ; i < Count; i++)
            {
                Console.WriteLine("before yoeld return "+str);
                yield return str;
                str += "b";
            }
        }
        static void Main(string[] args)
        {
            foreach (var str in AddAB(3))
            {
                Console.WriteLine(str);
            }
        }
    }
}

IEnumerable接口的GetEnumerator方法实现了IEnumerator枚举器类的实例。所以上文的代码是没问题的,后面会给大家示范用IEnumertor接口实现枚举器。

yield return语句的意思是你向我请求从枚举器产生的下一个元素。

每次执行到yield return就会返回到他调用者那,但还会执行yield return之后的语句,直到碰到下一条yield return时停止。这个状态一直持续到foreach语句的结束。

猜你喜欢

转载自www.cnblogs.com/AD-milk/p/12459944.html
今日推荐