转自, 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;
        }
    }
}
 

最新文章

  1. JS正则表达式总结
  2. AI方向
  3. html引入css文件
  4. UVa 1451 (数形结合 单调栈) Average
  5. C语言---注释
  6. Javascript中new
  7. 【转】Multithreaded Python Tutorial with the “Threadworms” Demo
  8. Greatest common divisor(gcd)
  9. apache 日志中记录代理IP以及真实客户端IP
  10. Python的基础--对象
  11. c++设计模式-----抽象工厂模式
  12. iOS开发中视图控制器ViewControllers之间的数据传递
  13. 教你用SVG画出一条龙
  14. [SCOI 2010]传送带
  15. 轻量级.Net Core服务注册工具CodeDi发布啦
  16. 处理SQL Server中的重复行
  17. 蓝书例题之UVa 10253 Series-Parallel Networks
  18. ElasticSearch权威指南学习(映射和分析)
  19. 自定义String
  20. SDN 期末作业验收

热门文章

  1. java基础(25):Properties、序列化流、打印流、commons-IO
  2. 2-How nginx processes a request
  3. Linux帮助——常用命令
  4. 前端开发JS——jQuery常用方法
  5. flex布局开发
  6. 做一个vue轮播图组件
  7. JavaScript初探 三 (学习js数组)
  8. 【原创】CentOS 7 安装解压版mysql5.7
  9. Oracle Merge Into 使用注意事项
  10. Ubuntu18.04安装Cuda10.1