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 浏览量

助力您的 职业生涯

完成该课程以获得认证

开始
广告