[转载] C#面向对象设计模式纵横谈——18 Iterator迭代器模式

本文详细介绍了如何使用C#实现泛型集合的迭代器模式,通过定义`IEnumerable`和`IEnumerator`接口,并提供`MyEnumerator`类来遍历集合元素。

主讲:李建忠

来源:http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/CsharpOOD.aspx

 

clip_image002

clip_image004

clip_image006

clip_image008

 

   1:  public interface IEnumerable
   2:  {
   3:      IEnumerator GetEnumerator();
   4:  }
   5:   
   6:  public interface IEnumerator
   7:  {
   8:      Object Current {get;}
   9:      bool Movenext();
  10:      void Reset();
  11:  }
  12:   
  13:  private class MyEnumerator: IEnumerator
  14:  {
  15:      int nIndex;
  16:      MyCollection collection;
  17:   
  18:      public MyEnumerator(MyCollection coll)
  19:      {
  20:          collection=coll;
  21:          nIndex=-1;
  22:      }
  23:   
  24:      public bool MoveNext()
  25:      {
  26:          nIndex++;
  27:          return (nIndex<collection.items.GetLength(0));
  28:      }
  29:   
  30:      public int Current
  31:      {
  32:          get
  33:          {
  34:              return (collection.items[nIndex]);
  35:          }
  36:      }
  37:   
  38:      public void Reset()
  39:      {
  40:          nIndex=-1;
  41:      }
  42:  }

 

clip_image010

clip_image012

clip_image014

转载于:https://www.cnblogs.com/6DAN_HUST/archive/2012/10/17/2727088.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值