yield return,yield break
2024-10-19 00:17:18
转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html
yield return 表示在迭代中下一个迭代时返回的数据,除此之外还有yield break, 其表示跳出迭代,为了理解二者的区别我们看下面的例子
class A : IEnumerable
{
private int[] array = new int[10];
{
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;
}
}
}
{
for (int i = 0; i < 10; i++)
{
if (i < 8)
{
yield return array[i];
}
else
{
yield break;
}
}
}
最新文章
- JS正则表达式总结
- AI方向
- html引入css文件
- UVa 1451 (数形结合 单调栈) Average
- C语言---注释
- Javascript中new
- 【转】Multithreaded Python Tutorial with the “Threadworms” Demo
- Greatest common divisor(gcd)
- apache 日志中记录代理IP以及真实客户端IP
- Python的基础--对象
- c++设计模式-----抽象工厂模式
- iOS开发中视图控制器ViewControllers之间的数据传递
- 教你用SVG画出一条龙
- [SCOI 2010]传送带
- 轻量级.Net Core服务注册工具CodeDi发布啦
- 处理SQL Server中的重复行
- 蓝书例题之UVa 10253 Series-Parallel Networks
- ElasticSearch权威指南学习(映射和分析)
- 自定义String
- SDN 期末作业验收