知识大全 C#迭代器
Posted 列子
篇首语:不怕学不成,就怕心不诚。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 C#迭代器相关的知识,希望对你有一定的参考价值。
C#迭代器 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
迭代器是 C# 中的新功能 迭代器是方法 get 访问器或运算符 它使您能够在类或结构中支持 foreach 迭代 而不必实现整个 IEnumerable 接口 您只需提供一个迭代器 即可遍历类中的数据结构 当编译器检测到迭代器时 它将自动生成 IEnumerable 或 IEnumerable 接口的 Current MoveNext 和 Dispose 方法
迭代器概述
迭代器是可以返回相同类型的值的有序序列的一段代码
迭代器可用作方法 运算符或 get 访问器的代码体
迭代器代码使用 yield return 语句依次返回每个元素 yield break 将终止迭代 有关更多信息 请参见 yield
可以在类中实现多个迭代器 每个迭代器都必须像任何类成员一样有唯一的名称 并且可以在 foreach 语句中被客户端代码调用 如下所示 foreach(int x in SampleClass Iterator )
迭代器的返回类型必须为 IEnumerable IEnumerator IEnumerable 或 IEnumerator
yield 关键字用于指定返回的值 到达 yield return 语句时 会保存当前位置 下次调用迭代器时将从此位置重新开始执行
迭代器对集合类特别有用 它提供一种简单的方法来迭代不常用的数据结构(如二进制树)
废话不说了 先举个列子供大家参考 public class DaysOfTheWeek : System Collections IEnumerable string[] m_Days = Sun Mon Tue Wed Thr Fri Sat ;
public System Collections IEnumerator GetEnumerator() for (int i = ; i < m_Days Length; i++) yield return m_Days[i];
class TestDaysOfTheWeek static void Main() // Create an instance of the collection class DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach foreach (string day in week) System Console Write(day + ); 运行结果为Sun Mon Tue Wed Thr Fri Sat 再举个列子 请你自己尝试开发一个小程序 要求使用迭代器输出春夏秋冬四个季节 方法当然和上面雷同 下面是具体的代码
using System; using System Collections Generic; using System Text;
namespace Test public class Year : System Collections IEnumerable//实现迭代器的类 string[] season = Spring Summer Autumn Winter ;
cha138/Article/program/net/201311/12348相关参考