提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。(foreach正是实现了可迭代才可用的方法)
下方给出自定义的类,并实现可迭代的案例,体会迭代器模式。
先给出说明:++a<0 是先加再比较 而a++<0是先比较a与0再加a !!!!!!
//自定义聚类 class DieDaiList : IEnumerable { private List<object> list = new List<object>() { "n","x","j"}; public int Length { get { return list.Count; } } public object GetElement(int index) { return list[index]; } public IEnumerator GetEnumerator() { return new DieDaiListor(this); } }
//对应的自定义迭代器类 class DieDaiListor : IEnumerator { private DieDaiList _diedailist;//包含自定义聚类 private int index;//与索引(因为foreach先执行MoveNext,再执行Current,因此初始化需要设置为-1) public DieDaiListor(DieDaiList diedailist) { _diedailist = diedailist; index = -1;//先执行MoveNext,再执行Current,因此这里设置-1 } public object Current { get { return _diedailist.GetElement(index); } } public bool MoveNext() { //++a<0 是先加再比较 而a++<0是先比较a与0再加a !!!!!! //先执行此,再执行Current if (++index< _diedailist.Length) { return true; } else { return false; } } public void Reset() { index = -1; } }
static void Main(string[] args) { DieDaiList dd = new DieDaiList(); foreach (var item in dd) { Console.WriteLine(item); } Console.ReadKey(); }
迭代器的实现就是上方所书写的,套路都是一样的哦,这就是迭代器模式!
原文:https://www.cnblogs.com/ningxinjie/p/12194352.html