最近在和同事说到迭代器的作用,当时就举了个例子,写一个Fibonacci数列,并且暂时不考虑int溢出的问题:
1 static IEnumerable<int> Fibonacci()
2 {
3 int prev = 0;
4 int current = 1;
5 while (true)
6 {
7 yield return current;
8 current = prev + (prev = current);
9 }
10 }
2 {
3 int prev = 0;
4 int current = 1;
5 while (true)
6 {
7 yield return current;
8 current = prev + (prev = current);
9 }
10 }