C#教程:C#2.0 新特性 迭代器
迭代器
迭代器是C# 2.0中的新功能。C# 2.0能在类或结构中支持foreach迭代,而不必实现整个IEnumerable接口。只需提供一个迭代器,即可遍历类中的数据结构。当编译器检测到迭代器时,它将自动生成IEnumerable或IEnumerable接口的Current、MoveNext和Dispose方法。创建了迭代器后,就可以使用foreach对类进行遍历,例如:
本教程来自http://www.isstudy.com
static void Main()
{
ListClass lc = new ListClass();
foreach (int i in lc)
{
System.Console.WriteLine(i);
}
}
创建迭代器最常用的方法是对IEnumerable接口实现GetEnumerator方法,例如:
public System.Collections.IEnumerator GetEnumerator()
{
for (int j = 0;j < max; j++)
{
yield returnj;
}
}
示例
迭代器的实现和使用
下面的示例代码演示了类Year实现迭代器及其使用方法。
public class Year : System.Collections.Ienumerable//实现迭代器的类
{
string[] season = { "Spring", "Summer", "Autumn", "Winter" };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < season.Length; i++)
{
yield return season [i];
}
}
}
class TestClass//使用实现迭代器的类
{
static void Main()
{
Year y= new Year ();
// 使用迭代器
foreach (string s in y)
{
System.Console.Write(s + " ");
}
}
}
输出结果:
Spring Summer Autumn Winter
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
本教程来自http://www.isstudy.com
using System;
using System.Collections.Generic;
using System.Text;
namespace _2_10
{
public class Year : System.Collections.IEnumerable //实现迭代器的类
{
string[] season = { "Spring", "Summer", "Autumn", "Winter" };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < season.Length; i++)
{
yield return season[i];
}
}
}
class TestClass //使用实现迭代器的类
{
static void Main(string[] args)
{
Year y = new Year();
// 使用迭代器
foreach (string s in y)
{
System.Console.Write(s + " ");
}
}
}
}