C# 中的迭代器


迭代器對集合執行自定義迭代。它使用 yield return 語句並一次返回一個元素。迭代器會記住當前位置,在下次迭代時返回下一個元素。

以下是一個示例 −

示例

 線上演示

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

namespace Demo {
   class Program {
      public static IEnumerable<string> display() {
         int[] arr = new int[] {99,45,76};

         foreach (var val in arr) {
            yield return val.ToString();
         }
      }

      public static void Main(string[] args) {
         IEnumerable<string> ele = display();
         foreach (var element in ele) {
            Console.WriteLine(element);
         }
      }
   }
}

輸出

99
45
76

上面,我們有一個名為 display() 的迭代器方法,該方法使用 yield 語句一次返回一個元素 −

public static IEnumerable<string> display() {
   int[] arr = new int[] {99,45,76};

   foreach (var val in arr) {
      yield return val.ToString();
   }
}

結果被儲存,每個元素被迭代並列印 −

IEnumerable<string> ele = display();
foreach (var element in ele) {
   Console.WriteLine(element);
}

更新時間: 2020-06-20

307 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.