1. 程式人生 > >C#基礎:迭代器原理

C#基礎:迭代器原理

在迭代器塊中,使用yield關鍵字返回給foreach迴圈中使用的值,下面是迭代器的原理。SimpleList()是迭代器塊。

  1.  public static IEnumerable SimpleList()//迭代器使用yield return返回值給foreach
  2.         {
  3.             yield return "string 1";
  4.             yield return "string 2";
  5.             yield return "string 3";
  6.         }
  7. static void Main(string[] args){
  8.        foreach(string a in SimpleList){
  9.        Console.WriteLine(a);
  10.        }
  11. }

例項程式碼如下,使用迭代器列印素數。素數是隻能被1和他本身整除的數,也叫質數。

  //迭代器

  1.     public class Primes {//迭代器類
  2.         private int min;//最小值
  3.         private int max;//最大值
  4.         public Primes() : this(2, 100) { }//預設構造(2,100)
  5.         public Primes(int min,int max) {
  6.             if (min < 2)
  7.             {
  8.                 this.min = 2;
  9.             }
  10.             else {
  11.                 this.min = min;
  12.             }
  13.             this.max = max;
  14.         }
  15.         public IEnumerator GetEnumerator() {//迭代器塊
  16.             bool isPrime = true;
  17.             for (int i = min; i <= max; i++)//迴圈輸出
  18.             {
  19.                 for (int j = 2; j <i; j++)//判斷能否能被2--->i-1之間的數整除
  20.                 {
  21.                     if (i % j == 0)//餘數是否為0,能整除,就不是素數
  22.                     {
  23.                         isPrime = false;
  24.                         break;
  25.                     }
  26.                     else if(i%j!=0){
  27.                         isPrime = true;
  28.                     }
  29.                 }
  30.                 if (isPrime)
  31.                 {
  32.                     yield return i;//返回給foreach要使用的值
  33.                 }
  34.             }
  35.         }
  36.     }

//Main()方法

  1. static void Main(string[] args){
  2.        Primes aa=new Primes(2,1000);
  3.        Primes bb=new Primes();//預設(2,100)
  4.        foreach(string a in aa){
  5.        Console.Write(a+"  ");
  6.        foreach(string b in bb){
  7.        Console.Write(a+"  ");
  8.          }
  9.        }
  10. }