zoukankan      html  css  js  c++  java
  • yield return,yield break

    转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html

    yield return 表示在迭代中下一个迭代时返回的数据,除此之外还有yield break, 其表示跳出迭代,为了理解二者的区别我们看下面的例子

    复制代码
    class A : IEnumerable
    {
        private int[] array = new int[10];

        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < 10; i++)
            {
                yield return array[i];
            }
        }
    }
     
     
    yield(C# 参考)
    在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
    yield return <expression>;
    yield break;

    备注 :
    计算表达式并以枚举数对象值的形式返回;expression 必须可以隐式转换为迭代器的 yield 类型。
    yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:
    不允许不安全块。
    方法、运算符或访问器的参数不能是 ref 或 out。
    yield 语句不能出现在匿名方法中。
    当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。
    yield return 提供了迭代器一个比较重要的功能,即取到一个数据后马上返回该数据,不需要全部数据装入数列完毕,这样有效提高了遍历效率。


    When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yieldto define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator<T> for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.
    复制代码

        如果你只想让用户访问ARRAY的前8个数据,则可做如下修改.这时将会用到yield break,修改函数如下

    复制代码
    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < 10; i++)
        {
            if (i < 8)
            {
                yield return array[i];
            }
            else
            {
                yield break;
            }
        }
    }
     
  • 相关阅读:
    django之orm单表查询
    python通过os.system()方法执行pscp提示却找不到该应用程序
    VUE 条件编译
    博客园Silence新主题美化,2021年最新更新!换个口味~
    JavaScript中数组的操作方法总汇
    Vue 上传材料(使用input)
    postgresql关于array类型有交集(包含查询数据任意元素,有重叠&&)的一些查询方法以及sqlalchemy语句实现
    linux便捷日志查询操作
    安装RabbitMQ
    v-model语法糖在input上组件上的使用
  • 原文地址:https://www.cnblogs.com/Fred1987/p/5932156.html
Copyright © 2011-2022 走看看