zoukankan      html  css  js  c++  java
  • 迭代器模式

    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 );
                }
            }
  • 相关阅读:
    原始字符串
    .Net Core 常见错误解决记录
    P1010 幂次方 P1022 计算器的改良
    P1036 选数
    广度优先遍历
    P4327 彼得潘框架
    链表
    标准库与标准模板库
    信息学竞赛打表犯规吗?
    对拍程序
  • 原文地址:https://www.cnblogs.com/wangchuang/p/3016761.html
Copyright © 2011-2022 走看看