iterator迭带输出:C#中的Iterator迭代器模式(行为型模式)来源: 发布时间:星期四, 2009年2月12日 浏览:212次 评论:0
迭代器模式我们在平时开发中应该经常用到不直接使用也会间接使用我们使用foreach语句来循环就是在间接使用迭代器模式 迭代器就像指针样可以向前向后移动,在.net中迭代器只能向后移动. 动机: 在软件Software构建过程中,集合对象内部结构常常变化各异但对于这些集合对象,我们希望在不暴露其内部结构同时可以让外部客户代码透明地访问其中包含元素;同时这种“透明遍历”也为“同种算法在多种集合对象上进行操作”提供了可能使用面向对象技术将这种遍历机制抽象为“迭代器对象”为“应对变化中集合对象”提供了种优雅方式 意图: 提供种思路方法顺序访问个集合对象中各个元素而不暴露该对象内部表示 /// <summary> /// 可迭代接口 /// </summary> public erface IEnumerable { //得到迭代器 IEnumerator GetEnumerator; } /// <summary> /// 迭代器接口 /// </summary> public erface IEnumerator { //得到当前对象 object Current { get; } bool MoveNext; void Re; } /// <summary> /// 集合类型,实现了可迭代接口 /// </summary> public MyCollection : IEnumerable { ernal items; public MyCollection { items = [5] {1, 2, 3, 4, 5}; } #region IEnumerable 成员 //实现迭代接口,返回迭代器 public IEnumerator GetEnumerator { //在这里进行解藕,将集合对象转换为迭代器 MyEnumerator(this); } #endregion } //迭代器对象,实现了迭代器接口 ernal MyEnumerator : IEnumerator { private nIndex; MyCollection collection; //构造将集合类型转换成内部成员 public MyEnumerator(MyCollection coll) { this.collection = coll; nIndex = -1; } #region IEnumerator 成员 //返回当前迭代到对象 public object Current { get { collection.items[nIndex]; } } //移动到下个对象,指针向后移动 public bool MoveNext { nIndex; (nIndex < collection.items.GetLength(0)); } //重设迭代器,指针回零 public void Re { nIndex = -1; } #endregion } 很清楚,在上面代码中,我们通过GetEnumerator思路方法,将集合对象转换为了可迭代对象这实际上是在对集合对象进行抽象将他转换为迭代器在这里我们需要定义个迭代器类但是这是.net 1.1中做法在.net 2.0以后实现个可迭代模式更加简单 /// <summary> /// 集合类型,实现了可迭代接口 /// </summary> public MyCollection : IEnumerable<> { ernal items; public MyCollection { items = [5] {1, 2, 3, 4, 5}; } #region IEnumerable<> 成员 public IEnumerator<> GetEnumerator { for( i = 0; i < items.Length; i) { yield items[i]; } } #endregion #region IEnumerable 成员 .Collections.IEnumerator .Collections.IEnumerable.GetEnumerator { for( i = 0; i < items.Length; i) { yield items[i]; } } #endregion } 我们通过yield 关键字来返回个IEnumerator接口这个关键在在编译的后会自动生成对应迭代器代码 在.net中迭代器只能先前在c中可以向后等其他操作 注意:在迭代过程中我们不能向集合添加内容后移除集合里item这样将会导致些问题出现. 0
相关文章读者评论发表评论 |