C# yield return 关键字的详解.doc

上传人:re****.1 文档编号:560573313 上传时间:2023-01-21 格式:DOC 页数:4 大小:34KB
返回 下载 相关 举报
C# yield return 关键字的详解.doc_第1页
第1页 / 共4页
C# yield return 关键字的详解.doc_第2页
第2页 / 共4页
C# yield return 关键字的详解.doc_第3页
第3页 / 共4页
C# yield return 关键字的详解.doc_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
资源描述

《C# yield return 关键字的详解.doc》由会员分享,可在线阅读,更多相关《C# yield return 关键字的详解.doc(4页珍藏版)》请在金锄头文库上搜索。

1、C# yield return 关键字的详解2009-10-19 10:42yield(C# 参考)在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:yield return ;yield break; 备注 :计算表达式并以枚举数对象值的形式返回;expression 必须可以隐式转换为迭代器的 yield 类型。yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:不允许不安全块。方法、运算符或访问器的参数不能是 ref 或 out。yield 语句不能出现在匿名方法中。当和 expre

2、ssion 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。yield return 提供了迭代器一个比较重要的功能,即取到一个数据后马上返回该数据,不需要全部数据装入数列完毕,这样有效提高了遍历效率。 以下是一个比较特殊的例子:using System;using System.Collections;using System.IO;using Microsoft.Office.Interop.PowerPoint;using Microsoft.Office.Core;using System.Windows.For

3、ms;using System.Threading;namespace test public class Persons : System.Collections.IEnumerable #region IEnumerable 成员 public System.Collections.IEnumerator GetEnumerator() yield return 1; Thread.Sleep(5000); yield return 2; Thread.Sleep(5000); yield return 3; Thread.Sleep(5000); yield return 4; Thre

4、ad.Sleep(5000); yield return 5; Thread.Sleep(5000); yield return 6; #endregion class program static void Main() Persons arrPersons = new Persons(); foreach (string s in arrPersons) System.Console.WriteLine(s); System.Console.ReadLine(); 每隔5秒钟, 控制台就会输出一个数据,直到全部数据输入完毕。12.4 C#迭代器在使用foreach语句时,需要在迭代的类中实

5、现IEnumerable接口或ICollection接口。这样做需要一个处理过程,从而变得有点麻烦。在C#中,引入迭代器这个概念后,就很好地解决了上述问题。只要在C#项目程序的类或结构中实现迭代器,那么这个类和结构就支持foreach迭代,而不再需要实现全部的IEnumerable接口。当编译器检测到迭代器时,项目程序将自动实现IEnumerable接口或实现IEnumerable接口的方法和属性。12.4.1 迭代器概述迭代器能够生成相同类型的有序代码块,通过上述代码块能够实现特定的处理功能。迭代器代码块和普通代码块类似,只是迭代器代码块里面存在不定量的yield语句。具体使用格式如下:fo

6、reach语句 表达式 yield return 成员; . yield break;其中,yield return语句生成迭代的下一个值;yield break语句设置迭代终止完成。即关键字yield用于设置返回值,当程序达到yield return语句时,会保存当前的位置。当下次调用迭代器时,将从这个位置重新开始执行。不用foreach , 直接用 IEnumerator 的方法实现迭代:如下using System;using System.Collections;using System.IO;using Microsoft.Office.Interop.PowerPoint;usin

7、g Microsoft.Office.Core;using System.Windows.Forms;using System.Threading;namespace test public class Persons : System.Collections.IEnumerable #region IEnumerable 成员 private static Random m_rand = new Random(); public System.Collections.IEnumerator GetEnumerator() while (true) yield return m_rand.Next(0,1000); Thread.Sleep(1000); #endregion class program static void Main() Persons arrPersons = new Persons(); IEnumerator array = arrPersons.GetEnumerator(); while (array.MoveNext() System.Console.WriteLine(array.Current.ToString(); System.Console.ReadLine();

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 生活休闲 > 社会民生

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号