迭代器模式就是循环输出一个集合的对象。LIST 本身就是微软给我们提供的迭代器模式。
如果我们要自己创建一个迭代器模式该如何去弄?
代码1:
public class Container { private List<int> ShowList = null; public Container(List<int> _ShowList) { ShowList = _ShowList; } private int i = 0; public int Get() { return ShowList[i++]; } public bool IsEnd() { return i == ShowList.Count; } }
代码2:
用微软提供的迭代器接口来做:IEnumerable
public class Collection : IEnumerable { private List<int> ShowList = null; public Collection(List<int> _ShowList) { ShowList = _ShowList; } private int i = 0; /// <summary> /// 如果要使用 forEach 就要定义这个地方 /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { while (i < ShowList.Count) yield return ShowList[i++]; } }
使用:
List<int> ShowList = new List<int>() { 1, 5, 8, 13, 20, 22, 30, 39, 48 }; ShowList.ForEach(i => Console.WriteLine(i)); Console.WriteLine("_____________________________________"); Container container = new Container(ShowList); while (!container.IsEnd()) { Console.WriteLine(container.Get()); } Console.WriteLine("_____________________________________"); Collection collection = new Collection(ShowList); foreach (var item in collection) { Console.WriteLine(item); } Console.ReadLine();
结果图:
总结:
这三种方式的结果完全一样,都实现了迭代器模式。