C# 中的迭代器函式


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

以下是示例 -

示例

 即時演示

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

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

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

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

輸出

99
45
76

上面,我們有迭代器方法 display(),它使用 yield 語句一次返回一個元素 -

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

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

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

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

更新時間:20-6 月-2020

689 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.