C#中yield用法
来源:互联网 发布:it行业发展趋势 编辑:程序博客网 时间:2024/05/17 21:52
yield关键字向编译器指示它所在的方法是迭代器块。编译器生成一个类来实现迭代器块中表示的行为。在迭代器块中,yield 关键字与return 关键字结合使用,向枚举器对象提供值。这是一个返回值,例如,在foreach 语句的每一次循环中返回的值。yield 关键字也可与break 结合使用,表示迭代结束。
例子:
yield return <expression>;
yield break;
在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:4 8 16 32 64 128 256 */
- C#中yield用法
- C#中yield用法
- C# 中 yield return 和 yield break 关键字的用法
- C# 中 yield return 和 yield break 关键字的用法
- c#中yield的用法详解
- C#中yield return用法分析
- C#中yield return用法分析
- C#中yield return用法分析
- C#中yield return用法分析
- C#中yield return用法分析
- C#中yield return用法分析
- python中yield用法
- python中yield用法
- python中yield用法
- python中yield用法
- python中yield用法
- C#编程中yield
- C# 中yield使用
- sql server 彻底理解锁机制(1)
- hdu1556 Color the ball
- UVALive 4327 Parade
- 安卓去标题 + handler
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)?
- C#中yield用法
- ArcGIS 缓存之显示缓存
- HTML的知识总结
- 在C++中打印出变量的方法
- 第一次创业还是失败了---分享失败的经验!!!
- 来自 360 团队的基于MySQL数据库中间层项目:Atlas
- thinking in java 学习4
- build/envsetup.sh 简介
- USACO 2.1.3 Sorting a Three-Valued Sequence 三值的排序