那些年我还不懂:IEnumerable,IEnumerator

来源:互联网 发布:淘宝评论在哪里 编辑:程序博客网 时间:2024/05/01 08:02

1、首先看一个简单的例子

int[] myArray = { 1, 32, 43, 343 };            IEnumerator myie = myArray.GetEnumerator();            myie.Reset();            while (myie.MoveNext())            {                int i = (int)myie.Current;                Console.WriteLine("Value: {0}", i);            }

相信很多人都不会像上面这样去遍历myArray这个数组,通常我们这样会这样做

      foreach (int item in myArray)                Console.WriteLine(item.ToString());

在大部分的情况下,很多人会使用for和foreach来遍历数组,而对于上面的语法却用的很少,但是对foreach的具体来历还很模糊!

2、理解foreach

大家都知道要实现foreach的必须要实现IEnumerable和IEnumerator的接口,只有实现了它们,才能实现遍历,所以要讲foreach的来历,必须要把那两个接口给搞清楚点!

这边也想说明一点的是:如果对这两个接口有了一定的了解后,只要实现那个GetEnumerator方法即可,而不需要实现于IEnumerable接口,这只是针对对这两个接口有一定了解的朋友!

2.1 IEnumerable具体的作用:就是使实现这个接口的对象成为可枚举类型。IEnumerable接口包含一个GetEnumerator方法,返回值为IEnumerator的类型!代码如下:
     public class MyColors : IEnumerable        {            string[] colors = { "Red", "Yellow", "Biue" };            public IEnumerator GetEnumerator()            {                return colors.GetEnumerator();            }        }
那么我们在客户端进行调用的时候就可以这样做了!
     MyColors colors = new MyColors();                foreach (string item in colors)                    Console.WriteLine(item);
这样就能使用实现这个接口的对象进行foreach遍历了,就是这么简单的一个列子,这边可能有的人会有疑问,我们就实现了IEnumerable接口但却没实现IEnumerator接口,可是我们不是说只有实现了这两个接口才可以进行foreach遍历吗?可以这样说当使用forach进行遍历的时候,编译器会到这个对象的类中去寻找GetEnumerator方法,找到这个方法后返回这个一个IEnumerator的对象(枚举数),而我这边返回的是“colors.GetEnumerator()”,是一个数组对象调用它本身中的“GetEnumerator”方法,所以说数组本身就实现了IEnumerator接口,那么两个接口都实现了,不就好实现foreach遍历了,其实在实现遍历枚举数的时候编译器会自动去调用数组中实现枚举数的类中的方法。2.2  IEnumerator接口的作用:实现可枚举数,首先看一下接口的定义:包含一个属性两个方法MoveNext → 把当前的项移动到下一项(类似于索引值),返回一个bool值,这个bool值用来检查当前项是否超出了枚举数的范围!Current → 获取当前项的值,返回一个object的类型(这边会涉及到装箱和拆箱的问题 → 后面讲泛型的时候会涉及到)!Reset → 顾名思义也就是把一些值恢复为默认值,比如把当前项恢复到默认状态值!
      public class MyIEnumerator : IEnumerator        {            public MyIEnumerator(string[] colors)            {                this.colors = new string[colors.Length];                for (int i = 0; i < this.colors.Length; i++)                    this.colors[i] = colors[i];            }           string[] colors;        //定义一个数组,用来存储数据            int position = -1;      //定义当前项的默认值,也就是索引值,一开始认识数组的索引从“0”开始,            //怎么默认设置他为“-1”呢,最后才想明白,这样设置是合情合理的!            public object Current       //根据当前项获取相应的值            {                get                {                    return colors[position];          //返回当前项的值,但是会做一个装箱的操作!                  }           }           public bool MoveNext()                  //移动到下一项            {              if (position < colors.Length - 1)     //这就是设置默认值为-1的根据                {                    position++;                    return true;              }              else              {                    return false;              }            }            //重置当前项的值,恢复为默认值            public void Reset()            {                this.position = -1;            }        }
上面讲到的IEnumerable接口中GetEnumerator方法是获取要遍历的枚举数,在我们没有创建自己的遍历枚举数的类时,我们使用的是Array的遍历枚举数的方法(关于数组的可枚举类型和枚举数会在下一篇讲到),但这个有的时候不一定适合我们,我们需要为自己定制一个更合适的,所以我们要创建自己的枚举数类(也就是上面的代码),把第三点和第四点的代码合并起来(改动一点代码),如下:
     public class MyColors   //: IEnumerable            {                string[] colors = { "Red", "Yellow", "Biue" };                public IEnumerator GetEnumerator()                {                    return new MyIEnumerator(colors);                }            }

3、关于可枚举类型和枚举数

①可枚举类型 → 实现IEnumerable接口,可以不需要直接实现这个接口,但必须有个GetEnumerator方法,返回值类型必须为IEnumerator类型,也就是第四点最后一段代码中接口注释的那种写法!

②枚举数 → 实现IEnumerator接口,实现全部方法,首先是调用GetEnumerator返回一个类型为IEnumerator的枚举数,然后编译器会隐式的调用实现IEnumerator类中的方法和属性!

总结:所以实现foreach遍历,必须达到上面的两种条件才能进行遍历对象,他们可以写在一起也可以分开,最好是分开,进行职责分离,一个类干一件事总归是好事!也满足面向对象的单一指责设计原则。

下面的代码示例演示如何实现自定义集合的 IEnumerable 和 IEnumerator 接口(代码来自MSDN)

using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    public class Person    {        public Person(string fName, string lName)        {            this.firstName = fName;            this.lastName = lName;        }        public string firstName;        public string lastName;    }    public class People : IEnumerable    {        private Person[] _people;        public People(Person[] pArray)        {            _people = new Person[pArray.Length];            for (int i = 0; i < pArray.Length; i++)            {                _people[i] = pArray[i];            }        }        IEnumerator IEnumerable.GetEnumerator()        {            return (IEnumerator)GetEnumerator();        }        public PeopleEnum GetEnumerator()        {            return new PeopleEnum(_people);        }    }    public class PeopleEnum : IEnumerator    {        public Person[] _people;        // Enumerators are positioned before the first element        // until the first MoveNext() call.        int position = -1;        public PeopleEnum(Person[] list)        {            _people = list;        }        public bool MoveNext()        {            position++;            return (position < _people.Length);        }        public void Reset()        {            position = -1;        }        object IEnumerator.Current        {            get            {                return Current;            }        }        public Person Current        {            get            {                try                {                    return _people[position];                }                catch (IndexOutOfRangeException)                {                    throw new InvalidOperationException();                }            }        }    }    class Program    {        static void Main(string[] args)        {            Person[] peopleArray = new Person[3]            {                new Person("John", "Smith"),                new Person("Jim", "Johnson"),                new Person("Sue", "Rabon"),            };            People peopleList = new People(peopleArray);            foreach (Person p in peopleList)                Console.WriteLine(p.firstName + " " + p.lastName);        }    }}
0 0