C# 中的迭代器函数
csharpprogrammingserver side programming更新于 2025/7/12 23:52:17
迭代器方法对集合执行自定义迭代。它使用 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);
}

