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-Jun-2020

686 瀏覽量

助力您的 職業生涯

完成該課程以獲得認證

開始
廣告