手動で小コードを書く-foreach実現メカニズム

7750 ワード

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;



namespace  

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] arr = { 1,2,3,4,6};

            IEnumerator ie = arr.GetEnumerator();

            while(ie.MoveNext()==true)

            {

                int i = (int)ie.Current;

                Console.WriteLine(i);

            }

            Console.ReadLine();

        }

    }

}

 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;



namespace  

{

    class ColorEnumerator:IEnumerator// IEnumerator 

    {

        string[] Colors;

        int Position = -1;

        // Current 

        public object Current

        {

            get

            { 

                if(Position==-1)

                {

                    throw new InvalidOperationException();// 

                }

                else if(Position==Colors.Length)

                {

                    throw new InvalidOperationException();

                }

                return Colors[Position];

            }

        }

        public bool MoveNext()

        {

            if (Position < Colors.Length - 1)

            {

                Position++;

                return true;

            }

            else

            {

                return false;

            }

        }

        public void Reset()

        {

            Position = -1;

        }

        public ColorEnumerator(string[]theColors)

        { 

            Colors=new string[theColors.Length];

            for (int i = 0; i < theColors.Length;i++ )

            {

                Colors[i]=theColors[i];

                Console.WriteLine(Colors[i]);

            }

        }

    }

}
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace  

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] arr = { "Red", "Blue", "Yellow", "Green", "Gray", "Orange" };

            ColorEnumerator color = new ColorEnumerator(arr);

            Console.ReadKey();

        }

    }

}