[行为型设计模式:游标模式]

来源:互联网 发布:mac cocoapods 升级 编辑:程序博客网 时间:2024/06/03 17:28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    public interface IEnumerator
    {
        int Current { get; }//原代码是OBJECT类型
        bool MoveNext();
        void Reset();
    }

    public class MyCollection : IEnumerable
    {
        int[] items;
        public MyCollection()
        {
            items = new int[5] { 3, 5, 5, 8, 10 };
        }
        public IEnumerator GetEnumerator()
        {
            return new MyEnumerator(this);
        }
        public class MyEnumerator : IEnumerator
        {
            int nindex;
            MyCollection collection;
            public MyEnumerator(MyCollection coll)
            {
                collection = coll;
                nindex = -1;
            }
            public bool MoveNext()
            {
                nindex++;
                return (nindex < collection.items.GetLength(0));
            }
            public int Current
            {
                get
                {
                    return (collection.items[nindex]);
                }
            }
            public void Reset()
            {
                nindex = 0;
            }
        }
    }
    public class APPFORITERATOR
    {
        public string ITERATOR()
        {
            MyCollection col = new MyCollection();
            string strReturn = string.Empty;
            //foreach (int i in col)
            //{
            //    strReturn = strReturn + i.ToString() + ",";
            //}
            ///下面的WHILE循环等价与上面的屏蔽代码
            IEnumerator ico = col.GetEnumerator();
            while (ico.MoveNext())
            {
                int i = (int)ico.Current;
                strReturn = strReturn + i.ToString() + ",";
            }
            return strReturn;
        }
    }
}


原创粉丝点击