using System;
using System.Collections;
using System.Collections.Generic;
class Program {
// *** 以前 ***
// 过去要让类型能用于 foreach,必须手写一个枚举器:
// 状态字段、MoveNext、Current 和 Reset
class EvenNumbersOld : IEnumerable {
int bound;
public EvenNumbersOld(int bound) { this.bound = bound; }
public IEnumerator GetEnumerator() { return new Enumerator(bound); }
class Enumerator : IEnumerator {
int bound, current;
public Enumerator(int bound) { this.bound = bound; this.current =
0; }
public bool MoveNext() { current += 2; return current <= bound; }
public object Current { get { return current; } }
public void Reset() { current = 0; }
}
}
// *** 在 2.0 版本中 ***
// yield return 会自动生成这个状态机
static IEnumerable<int> EvenNumbers(int bound) {
for (int n = 2; n <= bound; n += 2)
yield return n; // 方法在这里暂停
}
static IEnumerable<int> FirstThree(IEnumerable<int> source) {
int taken = 0;
foreach (int n in source) {
if (taken == 3) yield break; // 提前停止
taken++;
yield return n;
}
}
static void Main() {
foreach (int n in new EvenNumbersOld(10)) Console.Write(n + " ");
Console.WriteLine();
foreach (int n in EvenNumbers(10)) Console.Write(n + " ");
Console.WriteLine();
// 值逐个产生,所以无限的数据源也没问题
foreach (int n in FirstThree(EvenNumbers(int.MaxValue))) Console.Write(
n + " ");
Console.WriteLine();
}
}