电子商务网站建设实验指导,网站建设广州天河,网站开发网站制作报价单,南京哪家网站做的好下面内容节选至MSDN2005。迭代器#xff08;C# 编程指南#xff09; 迭代器是 C# 2.0 中的新功能。迭代器是方法、get 访问器或运算符#xff0c;它使您能够在类或结构中支持 foreach 迭代#xff0c;而不必实现整个 IEnumerable 接口。您只需提供一个迭代器#xff0c;即…下面内容节选至MSDN2005。迭代器C# 编程指南 迭代器是 C# 2.0 中的新功能。迭代器是方法、get 访问器或运算符它使您能够在类或结构中支持 foreach 迭代而不必实现整个 IEnumerable 接口。您只需提供一个迭代器即可遍历类中的数据结构。当编译器检测到迭代器时它将自动生成 IEnumerable 或 IEnumerable 接口的 Current、MoveNext 和 Dispose 方法。 迭代器概述 迭代器是可以返回相同类型的值的有序序列的一段代码。 迭代器可用作方法、运算符或 get 访问器的代码体。 迭代器代码使用 yield return 语句依次返回每个元素。yield break 将终止迭代。有关更多信息请参见 yield。 可以在类中实现多个迭代器。每个迭代器都必须像任何类成员一样有唯一的名称并且可以在 foreach 语句中被客户端代码调用如下所示foreach(int x in SampleClass.Iterator2){} 迭代器的返回类型必须为 IEnumerable、IEnumerator、IEnumerable 或 IEnumerator。 yield 关键字用于指定返回的值。到达 yield return 语句时会保存当前位置。下次调用迭代器时将从此位置重新开始执行。 迭代器对集合类特别有用它提供一种简单的方法来迭代不常用的数据结构如二进制树。 备注 yield 语句只能出现在 iterator 块中该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制 不允许不安全块。 方法、运算符或访问器的参数不能是 ref 或 out。 yield 语句不能出现在匿名方法中。有关更多信息请参见匿名方法C# 编程指南。 当和 expression 一起使用时yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。示例 说明 在本示例中DaysOfTheWeek 类是将一周中的各天作为字符串进行存储的简单集合类。foreach 循环每迭代一次都返回集合中的下一个字符串。 C#public class DaysOfTheWeek : System.Collections.IEnumerable{ string[] m_Days { Sun, Mon, Tue, Wed, Thr, Fri, Sat }; public System.Collections.IEnumerator GetEnumerator() { for (int i 0; 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 在下面的示例中迭代器块这里是方法 Power(int number, int power)中使用了 yield 语句。当调用 Power 方法时它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable一种迭代器接口类型。// yield-example.csusing System;using System.Collections;public class List{ 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); } }} 输出2 4 8 16 32 64 128 256 转载于:https://www.cnblogs.com/Sandheart/archive/2006/11/13/559063.html