C#编程-94:迭代器Iterator简单实例

109 阅读1分钟

\

  1. using System;

  2. using System.Collections;

  3. using System.Collections.Generic;

  4. using System.Linq;

  5. using System.Text;

  6.  

  7. namespace IEnumerableTest

  8. {

  9.     class Program

  10.     {

  11.         public static IEnumerable GetNextValue()

  12.         {

  13.             yield return "111111";

  14.             yield return "222222";

  15.             yield return "333333";

  16.             yield return "444444";

  17.             yield break;

  18.             yield return "555555";

  19.         }

  20.         static void Main(string[] args)

  21.         {

  22.             Console.WriteLine("===迭代成员===");

  23.             foreach (string item in GetNextValue())

  24.             {

  25.                 Console.WriteLine(item);

  26.             }

  27.  

  28.             Console.WriteLine("===迭代类===");

  29.             Months months = new Months();

  30.             foreach (string item in months)

  31.             {

  32.                 Console.WriteLine(item);

  33.             }

  34.             Console.ReadKey();

  35.         }

  36.     }

  37.  

  38.     class Months : IEnumerable

  39.     {

  40.         string[] months = { "January","February","March","April","May","June","July","August","September","October","November","December"};

  41.         public IEnumerator GetEnumerator()

  42.         {

  43.             for (int i = 0; i < months.Length; i++)

  44.             { 

  45.                 yield return months[i];

  46.             }

  47.         }

  48.     }

  49. }

\

C#编程-94:迭代器Iterator简单实例

C#编程-94:迭代器Iterator简单实例

C#编程-94:迭代器Iterator简单实例

C#编程-94:迭代器Iterator简单实例

C#编程-94:迭代器Iterator简单实例

C#编程-94:迭代器Iterator简单实例
\

\

\