在上一篇日志中说的手动实现枚举器来枚举自定义的类型,
http://blog.csdn.net/weixingstudio/article/details/6817319
可以看到过程非常复杂,而且容易出错。为了减轻程序员的负担,C#还提供了迭代器来帮助程序员完成其中的大部分工作。
迭代器(iterator)是能生成已排序值序列的一个代码块。迭代器实质上并不是一个可枚举的类的成员,迭代器只是指定了一个序列,枚举器应该用这个序列来返回其中的值。也就是说,迭代器只是对枚举序列的一个描述,C#编译器可以利用它来创建自己的枚举器。
下面看代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Iterator
{
class Program
{
static void Main(string[] args)
{
MyCollection<string> collect = new MyCollection<string>();
collect.FillList("china","american","australia","germany","japan","korea","canada");
foreach (string t in collect)
{
Console.WriteLine(t);
}
}
}
class MyCollection<T> : IEnumerable<T>
{
private List<T> myList=new List<T>();
public void FillList(params T[] items)
{
foreach(T t in items)
{
myList.Add(t);
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
foreach (var t in myList)
{
yield return t;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
//throw new NotImplementedException();
return null;
}
}
}
MyCollection 这个类实现了Ienumerable<T>接口,并且是显示的实现。在GetEnumerator() 方法中,通过yield 关键字返回要获取的数据。
yield 说明:yield 关键字制订了每一次迭代要反悔的值,它临时将方法叫停,将一个值传给调用者。当调用者需要下一个值时,GetEnumerator() 方法就从上次暂停的地方继续,生成下一个值。最终所有的数据都被访问,GetEnumerator()方法将终止。
|