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

Yield介绍

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

结合使用,表示迭代结束。

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

2.yield break;

System.Collections.Generic.IEnumerable<T>)或 Dispose 方法。

Yield使用约束

 

这类方法、运算符或访问器的体受以下约束的控制:

  • 不允许不安全块。

  • out。

  • 该语句可放在后跟 finally 块的 try 块中。

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

匿名方法(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
*/

 

相关文章:

  • 2022-12-23
  • 2021-04-01
  • 2021-10-15
  • 2022-12-23
  • 2021-08-20
  • 2021-10-26
  • 2021-12-07
猜你喜欢
  • 2021-08-13
  • 2021-07-14
  • 2022-12-23
  • 2022-02-08
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案