知识点 C#2.0新特性之迭代器, Yield Return

引子:http://www.cnblogs.com/yank/archive/2011/07/02/2096240.html

Yield介绍

yield关键字向编译器指示它所在的方法是迭代器块。

在迭代器块中,yield 关键字与 return 关键字结合使用,向枚举器对象提供一个返回值,例如,在 foreach 语句的每一次循环中返回的值。yield 关键字也可与 break 结合使用,表示迭代结束。

1.yield return <expression>;
在 yield return 语句中,将计算 expression 并将结果以值的形式返回给枚举器对象;expression 必须可以隐式转换为 yield 类型的迭代器。

2.yield break;

yield break 语句中,控制权将无条件地返回给迭代器的调用方,该调用方为枚举器对象的 IEnumerator.MoveNext 方法(或其对应的泛型 System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。

Yield使用约束

 

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

  • 不允许不安全块。

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

  • yield return 语句不能放在 try-catch 块中的任何位置。该语句可放在后跟 finally 块的 try 块中。

  • yield break 语句可放在 try 块或 catch 块中,但不能放在 finally 块中。

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

当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。

Yield使用示例

public class List

{

  //using System.Collections;

  public static IEnumerable Power(int number, int exponent)

  {

    int counter =0;

 

    int result =1;
    while (counter++< exponent)
    {
      result = result * number;
      yieldreturn result;
    }
  }
  staticvoid Main()
  {

    // Display powers of 2 up to the exponent 8:

    foreach (int i in Power(2, 8))

    {

      Console.Write("{0} ", i);
    }
  }
}
/*Output:
2 4 8 16 32 64 128 256
*/

原文地址:https://www.cnblogs.com/raysbo/p/2126570.html