天天看點

C# 自定義集合之疊代器

疊代器

基于自定義集合

//疊代器
    public class MysetIEnumerator <T> : IEnumerator   //具體的疊代器
    {

        private int position; //目前疊代器所指向的位置
        private Myset<T> myset;

        public MysetIEnumerator(Myset<T>myset )
        {
            //預設從頭開始
            position = -1;
            this.myset = myset;
        }

        public object Current
        {
            get
            {
                return myset[position];
            }
        }

        //調用一次MoveNext current就往後一位,最後就傳回false
        public bool MoveNext()
        {
            position++;
            //判斷position還在不在集合的範圍之内
            if (position < myset.Count)
            {
                return true;
            }

            return false;
        }

        public void Reset()
        {
            //重置一下
            position = -1;
        }
    }
           

測試

class TestMyset
    {
        static void Main(string[] args)
        {
            Myset<int> myset = new Myset<int>();
            myset.Add(1);
            myset.Add(2);
            myset.Add(3);
            myset.Add(4);
            
 
            foreach(int i in myset)
            {
                  //測試輸出
                Console.WriteLine(" i : {0} ", i, myset[1]);
            }

            Console.ReadLine();
        }
    }
           
c#