zoukankan      html  css  js  c++  java
  • C#中yield用法

    yield 关键字向编译器指示它所在的方法是迭代器块。编译器生成一个类来实现迭代器块中表示的行为。在迭代器块中,yield 关键字与 return 关键字结合使用,向枚举器对象提供值。这是一个返回值,例如,在 foreach 语句的每一次循环中返回的值。yield 关键字也可与 break 结合使用,表示迭代结束。

    例子:
    yield return <expression>;
    yield break;

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

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

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

    • 不允许不安全块。

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

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

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

     

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

    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;
    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);
    }
    }
    }
    /*
    Output:
    2 4 8 16 32 64 128 256
    */

  • 相关阅读:
    Spring restful
    LDAP & Implementation
    Restful levels and Hateoas
    事务隔离的级别
    servlet injection analysis
    session and cookie
    write RE validation
    hello2 source analysis
    匿名函数和递归函数
    生成器和迭代器,列表推导式
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/5566619.html
Copyright © 2011-2022 走看看