天天看點

C#程式設計-94:疊代器Iterator簡單執行個體

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace IEnumerableTest
{
    class Program
    {
        public static IEnumerable GetNextValue()
        {
            yield return "111111";
            yield return "222222";
            yield return "333333";
            yield return "444444";
            yield break;
            yield return "555555";
        }
        static void Main(string[] args)
        {
            Console.WriteLine("===疊代成員===");
            foreach (string item in GetNextValue())
            {
                Console.WriteLine(item);
            }
 
            Console.WriteLine("===疊代類===");
            Months months = new Months();
            foreach (string item in months)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
 
    class Months : IEnumerable
    {
        string[] months = { "January","February","March","April","May","June","July","August","September","October","November","December"};
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < months.Length; i++)
            { 
                yield return months[i];
            }
        }
    }
}      
C#程式設計-94:疊代器Iterator簡單執行個體
C#程式設計-94:疊代器Iterator簡單執行個體
C#程式設計-94:疊代器Iterator簡單執行個體
C#程式設計-94:疊代器Iterator簡單執行個體
C#程式設計-94:疊代器Iterator簡單執行個體
C#程式設計-94:疊代器Iterator簡單執行個體