C#关键字之yield

 

说起yield,不得不先说说迭代器。
迭代器是C# 2.0中的新功能,有了它,我们就可以在自己的类或者结构中支持foreach迭代而不必实现整个IEnumerable接口,我们只需要提供一个迭代器,即可遍历类中的数据结构。当编译器检测到迭代器时,它将自动生成IEnumerable接口的Current、MoveNext和Dispose方法。
而迭代器代码使用yield return语句依次返回每个元素。yield break将中止迭代。到达yield return语句时,会保存当前迭代的位置,下次调用迭代器时将从此位置开始执行。

在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。

  1. // yield-example.cs
  2. using System;
  3. using System.Collections;
  4. public class List
  5. {
  6.     public static IEnumerable Power(int number, int exponent)
  7.     {
  8.         int counter = 0;
  9.         int result = 1;
  10.         while (counter++ < exponent)
  11.         {
  12.             result = result * number;
  13.             yield return result;
  14.         }
  15.     }
  16.     static void Main()
  17.     {
  18.         // Display powers of 2 up to the exponent 8:
  19.         foreach (int i in Power(2, 8))
  20.         {
  21.             Console.Write("{0} ", i);
  22.         }
  23.     }
  24. }

 

yield(C# 参考)

 

在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:

复制代码
yield return <expression>;
yield break;

计算表达式并以枚举数对象值的形式返回;expression 必须可以隐式转换为迭代器的 yield 类型。

yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:

  • 不允许不安全块。

  • 方法、运算符或访问器的参数不能是 ref 或 out。

yield 语句不能出现在匿名方法中。有关更多信息,请参见匿名方法(C# 编程指南)。

当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。有关更多信息,请参见异常处理语句(C# 参考)。

在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。

复制代码
// 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);
        }
    }
}

输出

2 4 8 16 32 64 128 256 
http://msdn.microsoft.com/zh-cn/library/9k7k7cf0(VS.80).aspx

你可能感兴趣的:(C#关键字之yield)