c# 使用迭代器来创建可枚举类型

时间:2021-02-21 14:29:04
 class Program
    {
        public IEnumerator<string> GetEnumerator()
        {
            IEnumerable<string> my = BlackAndWhite();
            return my.GetEnumerator();
        }

        public IEnumerable<string> BlackAndWhite()
        {
            yield return "black";
            yield return "gray";
            yield return "white";
        }

        static void Main(string[] args)
        {
            Program program = new Program();

            foreach (var item in program)
            {
                Console.WriteLine(item);
            }
            foreach (var item in program.BlackAndWhite())
            {
                Console.WriteLine(item);
            }
        }
    }