迭代器的实现

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6. public class MyCollection : IEnumerable
  7. {
  8.     public int[] items;
  9.     public MyCollection()
  10.     {
  11.         items = new int[5] { 12, 44, 33, 2, 50 };
  12.     }
  13.     //public IEnumerator GetEnumerator()
  14.     //{
  15.     //    return new MyEnumerator(this);
  16.     //}
  17.     //c#2.0后的实现方式
  18.     public IEnumerator GetEnumerator()
  19.     {
  20.         for (int i = 0; i < items.Length; i++)
  21.         {
  22.             yield return items[i];
  23.         }
  24.     }
  25. }
  26. public class MyEnumerator : IEnumerator
  27. {
  28.     int nIndex;
  29.     MyCollection collection;
  30.     public MyEnumerator(MyCollection coll)
  31.     {
  32.         collection = coll;
  33.         nIndex = -1;
  34.     }
  35.     public bool MoveNext()
  36.     {
  37.         nIndex++;
  38.         return (nIndex < collection.items.GetLength(0));
  39.     }
  40.     public object Current
  41.     {
  42.         get
  43.         {
  44.             return (collection.items[nIndex]);
  45.         }
  46.     }
  47.     public void Reset()
  48.     {
  49.         nIndex = -1;
  50.     }
  51. }
  52. public class MainClass
  53. {
  54.     public static void Main()
  55.     {
  56.         MyCollection col = new MyCollection();
  57.         foreach (int i in col)
  58.         {
  59.             Console.WriteLine(i);
  60.         }
  61.         Console.WriteLine("-----------------------");
  62.         //完全抽象于(不依赖于)具休集合结构的访问操作
  63.         IEnumerator ietor = col.GetEnumerator();
  64.         while (ietor.MoveNext())
  65.         {
  66.             int i = (int)ietor.Current;
  67.             Console.WriteLine(i);
  68.         }
  69.         Console.ReadKey();
  70.     }
  71. }

        在软件构建过程中,集合对象内部结构常常变化各  异。但对于这些集合对象,我们希望在不暴露其内 部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为“同一种算 法在多种集合对象上进行操作”提供了可。

           使用面向对象技术将这种遍历机制抽象为“迭代器 对象”为“应对变化中的集合对象”提供了一种优雅的方式。

         

               意图:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。

Iterator模式的几个要点

  *  迭代抽象:访问一个聚合对象的内容而无 需暴露它的内部表示。

  *  迭代多态:为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作。

  *  迭代器的健壮性考虑:遍历的同时更改迭代器所在的集合结构,会导致问题。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值