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 块中,这种块可作为方法、运算符或访问器的主体实现。这类方法、运算符或访问器的体受以下约束的控制:

    • 不允许不安全块。

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

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

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

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

    当和 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 
    */
  • 相关阅读:
    Some ArcGIS Tools
    Optimization Algorithms
    BPTT
    Markdown 简明语法
    【转载】softmax的log似然代价函数(求导过程)
    DP tricks and experiences
    Google Chrome Keyboard Shortcuts
    【转载】如何掌握所有的程序语言
    转 C++ 面向对象程序设计的基本特点
    leetcode 18. 4Sum
  • 原文地址:https://www.cnblogs.com/Jeremy2001/p/6139562.html
Copyright © 2011-2022 走看看