现在的位置: 首页 > 综合 > 正文

Jack’s Notes5——foreach的本质(通过IEnumerable接口实现遍历)

2013年12月01日 ⁄ 综合 ⁄ 共 1635字 ⁄ 字号 评论关闭

         class
Program

    {

                   //5Main函数中的内容是foreach的内部实现过程

        static
void
Main(string[] args)

        {

                            //5.1实例化需要遍历的类,调用GetEnumerator()方法获得其可遍历的对象

            MyColors colors = new MyColors();

            IEnumerator colorEnumerator = colors.GetEnumerator();

                            //5.2使用MoveNext()方法和Current属性通过while循环实现foreach遍历

            while (colorEnumerator.MoveNext())

            {

                Console.WriteLine(colorEnumerator.Current);

            }

            Console.ReadKey();

        }

    }

        

         //1、定义一个实现了IEnumerable接口的类

    class
MyColors
:IEnumerable

    {

        public
string
[] Colors = { "Red",
"Yellow"
, "Blue" };

                   //2、该类有GetEnumerator()方法,返回一个实现了IEnumerator接口的类,将需要遍历的值传入该类

        public IEnumerator GetEnumerator()

        {

            return
new
ColorEnumerator(Colors);

        }

    }

        

         //3、该类实现了IEnumeratorCurrent属性和MoveNext()Reset()方法,用于实现foreach遍历

    class
ColorEnumerator
:IEnumerator

    {

        string[] enumColors;

 

        int index = -1;

                   //4、重写构造函数,使需要遍历的值可以通过构造函数传进来

        public ColorEnumerator(string[] colors)

        {

            enumColors = new
string
[colors.Length];

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

            {

                enumColors[i] = colors[i];

            }

        }

 

        public
object
Current

        {

            get {
return
enumColors[index]; }

        }

 

        public
bool
MoveNext()

        {

            if (index < enumColors.Length - 1)

            {

                index++;

                return
true
;

            }

            else

            {

                return
false
;

            }

        }

 

        public
void
Reset()

        {

            index = -1;

        }

    }

 

抱歉!评论已关闭.