在新接触c#2.0的时候无意间发现一个新的单词 yield,回想一下好像在1.1中没有看到过,查查msdn果然没有。
回过头在到2.0的sdk查到了 yield的说明,在sdk中的解释:
Used in an Iterators (C#) block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:
yield return expression;
yield break;
// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write("{0} ", i);
}
}
刚开始有点不明白,再看看例子就清楚很多了。以后写代码又可以省很多功夫了。