C# 迭代器
2018-01-22 17:10 更新
C# 迭代器
foreach 语句是枚举器的消费者。
迭代器是枚举器的生成器。
在这个例子中,我们使用迭代器返回一系列斐波纳契数:
using System;
using System.Collections.Generic;
class Main {
static void Main() {
foreach (int fib in Fibs(6)){
Console.Write (fib + " ");
}
}
static IEnumerable<int> Fibs (int fibCount) {
for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++) {
yield return prevFib;
int newFib = prevFib+curFib;
prevFib = curFib;
curFib = newFib;
}
}
}
yield return语句返回该枚举器的下一个元素。
迭代器语义
迭代器是一个包含一个或多个 yield 语句的方法,属性或索引器。
迭代器必须返回以下四个接口之一:
// Enumerable interfaces System.Collections.IEnumerable System.Collections.Generic.IEnumerable<T> // Enumerator interfaces System.Collections.IEnumerator System.Collections.Generic.IEnumerator<T>
允许多个yield语句。 例如:
class Test {
static void Main() {
foreach (string s in Foo())
Console.WriteLine(s); // Prints "One","Two","Three"
}
static IEnumerable<string> Foo() {
yield return "One";
yield return "Two";
yield return "Three";
}
}
yield break
yield break 语句指示迭代器块应提早退出,而不返回更多元素。
以下代码显示了如何使用yield break:
static IEnumerable<string> Foo (bool breakEarly) {
yield return "One";
yield return "Two";
if (breakEarly)
yield break;
yield return "Three";
}
返回语句在迭代器块中是非法的,请使用yield break。
编写序列
以下代码显示了如何仅输出斐波纳契数字:
using System;
using System.Collections.Generic;
class Main {
static void Main() {
foreach (int fib in EvenNumbersOnly (Fibs(6)))
Console.WriteLine (fib);
}
static IEnumerable<int> Fibs (int fibCount) {
for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++) {
yield return prevFib;
int newFib = prevFib+curFib;
prevFib = curFib;
curFib = newFib;
}
}
static IEnumerable<int> EvenNumbersOnly (IEnumerable<int> sequence) {
foreach (int x in sequence)
if ((x % 2) == 0)
yield return x;
}
}
以上内容是否对您有帮助:
← C# 枚举

免费 AI IDE


更多建议: