迭代器模式

public interface IEnumerable
{
IEnumerator GetEnumerator();
}
    public interface IEnumerator
    {
        int Current { get;}
        bool MoveNext();
        void Reset();
    }
 public class MyCollection:IEnumerable
    {
        public int[] items;

        public MyCollection()
        {
            items = new int[ 5 ] { 12, 44, 33, 2, 50 };
        }

        public IEnumerator GetEnumerator()
        {
            return new MyEnumerator( this );
        }
    }
 public class MyEnumerator:IEnumerator
    {
        int nIndex;
        MyCollection collection;

        public MyEnumerator( MyCollection coll )
        {
            this.collection = coll;
            nIndex = -1;
        }

        public int Current
        {
            get { return collection.items[ nIndex ]; }
        }

        public bool MoveNext()
        {
            nIndex++;
            return ( nIndex < collection.items.GetLength(0) );
        }

        public void Reset()
        {
            nIndex = -1;
        }
    }

调用

  static void Main( string[] args )
        {
            MyCollection col = new MyCollection();
            
            foreach( int i in col )
            {
                Console.WriteLine( i );
            }

            IEnumerator ietor = col.GetEnumerator();

            while( ietor.MoveNext() )
            {
                int i = (int)ietor.Current;
                Console.WriteLine( i );
            }
        }
原文地址:https://www.cnblogs.com/wangchuang/p/3016761.html