IEnumerable和IEnumerator 总结

在使用在使用Foreach遍历的时候它其实是转换为While,MoveNext()的形式的,所以你这个遍历对象必须是一个可枚举的类型,具有MoveNext()方法。
 
实现IEnumerable主要用来进行foreach遍历的,在Linq中经常会用到,IEnumerator是真正的集合访问器,

 初学C#的时候,老是被IEnumerable、IEnumerator、ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质。
下面我们先看IEnumerable和IEnumerator两个接口的语法定义 。其实IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个Current属性,来获取当前集合中的项吧。
MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?


详细讲解:
说到IEnumerable总是会和IEnumerator、foreach联系在一起。
C# 支持关键字foreach,允许我们遍历任何数组类型的内容:
//遍历数组的项
int[] myArrayOfInts = {10,20,30,40};
foreach(int i in my myArrayOfInts)
{
    Console.WirteLine(i);
}
虽然看上去只有数组才可以使用这个结构,其实任何支持GetEnumerator()方法的类型都可以通过foreach结构进行运算。
[csharp] view plaincopy
public class Garage
{
    Car[] carArray = new Car[4]; //在Garage中定义一个Car类型的数组carArray,其实carArray在这里的本质是一个数组字段
 
    //启动时填充一些Car对象
    public Garage()
    {
        //为数组字段赋值
        carArray[0] = new Car("Rusty", 30);
        carArray[1] = new Car("Clunker", 50);
        carArray[2] = new Car("Zippy", 30);
        carArray[3] = new Car("Fred", 45);
    }
}
理想情况下,与数据值数组一样,使用foreach构造迭代Garage对象中的每一个子项比较方便:
[csharp] view plaincopy
//这看起来好像是可行的
lass Program
   {
       static void Main(string[] args)
       {
           Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
           Garage carLot = new Garage();
 
           //交出集合中的每一Car对象吗
            foreach (Car c in carLot)
           {
               Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
           }
 
           Console.ReadLine();
       }
   }
让人沮丧的是,编译器通知我们Garage类没有实现名为GetEnumerator()的方法(显然用foreach遍历Garage对象是不可能的事情,因为Garage类没有实现GetEnumerator()方法,Garage对象就不可能返回一个IEnumerator对象,没有IEnumerator对象,就不可能调用方法MoveNext(),调用不了MoveNext,就不可能循环的了)。这个方法是有隐藏在System.collections命名空间中的IEnumerable接口定义的。(特别注意,其实我们循环遍历的都是对象而不是类,只是这个对象是一个集合对象)
支持这种行为的类或结构实际上是宣告它们向调用者公开所包含的子项:
//这个接口告知调方对象的子项可以枚举
public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
可以看到,GetEnumerator方法返回对另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,调用方可以用来移动IEnumerable兼容容器包含的内部对象。
//这个接口允许调用方获取一个容器的子项
public interface IEnumerator
{
    bool MoveNext(); //将游标的内部位置向前移动
    object Current{get;} //获取当前的项(只读属性)
    void Reset(); //将游标重置到第一个成员前面
}
所以,要想Garage类也可以使用foreach遍历其中的项,那我们就要修改Garage类型使之支持这些接口,可以手工实现每一个方法,不过这得花费不少功夫。虽然自己开发GetEnumerator()、MoveNext()、Current和Reset()也没有问题,但有一个更简单的办法。因为System.Array类型和其他许多类型(如List)已经实现了IEnumerable和IEnumerator接口,你可以简单委托请求到System.Array,如下所示:
[csharp] view plaincopy
namespace MyCarIEnumerator
{
    public class Garage:IEnumerable
    {
        Car[] carArray = new Car[4];
 
        //启动时填充一些Car对象
        public Garage()
        {
            carArray[0] = new Car("Rusty", 30);
            carArray[1] = new Car("Clunker", 50);
            carArray[2] = new Car("Zippy", 30);
            carArray[3] = new Car("Fred", 45);
        }
        public IEnumerator GetEnumerator()
        {
            return this.carArray.GetEnumerator();
        }
    }
}
//修改Garage类型之后,就可以在C#foreach结构中安全使用该类型了。
[csharp] view plaincopy
//除此之外,GetEnumerator()被定义为公开的,对象用户可以与IEnumerator类型交互:
namespace MyCarIEnumerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
            Garage carLot = new Garage();
 
            //交出集合中的每一Car对象吗
            foreach (Car c in carLot) //之所以遍历carLot,是因为carLot.GetEnumerator()返回的项时Car类型,这个十分重要
            {
                Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
            }
 
            Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");
            //手动与IEnumerator协作
            IEnumerator i = carLot.GetEnumerator();
            while (i.MoveNext())
            {
                Car myCar = (Car)i.Current;
                Console.WriteLine("{0} is going {1} MPH", myCar.CarName, myCar.CurrentSpeed);
            }
            Console.ReadLine();
        }
    }
}
 
下面我们来看看手工实现IEnumberable接口和IEnumerator接口中的方法:
[csharp] view plaincopy
namespace ForeachTestCase
{
      //继承IEnumerable接口,其实也可以不继承这个接口,只要类里面含有返回IEnumberator引用的GetEnumerator()方法即可
    class ForeachTest:IEnumerable {
        private string[] elements; //装载字符串的数组
        private int ctr = 0; //数组的下标计数器
 
        /// <summary>
        /// 初始化的字符串
        /// </summary>
        /// <param name="initialStrings"></param>
        ForeachTest(params string[] initialStrings)
        {
            //为字符串分配内存空间
            elements = new String[8];
            //复制传递给构造方法的字符串
            foreach (string s in initialStrings)
            {
                elements[ctr++] = s;
            }
        }
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="source">初始化的字符串</param>
        /// <param name="delimiters">分隔符,可以是一个或多个字符分隔</param>
        ForeachTest(string initialStrings, char[] delimiters)
        {
            elements = initialStrings.Split(delimiters);
        }
 
        //实现接口中得方法
        public IEnumerator GetEnumerator()
        {
            return new ForeachTestEnumerator(this);
        }
 
        private class ForeachTestEnumerator : IEnumerator
        {
            private int position = -1;
            private ForeachTest t;
            public ForeachTestEnumerator(ForeachTest t)
            {
                this.t = t;
            }
 
            #region 实现接口
 
            public object Current
            {
                get
                {
                    return t.elements[position];
                }
            }
 
            public bool MoveNext()
            {
                if (position < t.elements.Length - 1)
                {
                    position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }
 
            public void Reset()
            {
                position = -1;
            }
 
            #endregion
        }
        static void Main(string[] args)
        {
            // ForeachTest f = new ForeachTest("This is a sample sentence.", new char[] { ' ', '-' });
            ForeachTest f = new ForeachTest("This", "is", "a", "sample", "sentence.");
            foreach (string item in f)
            {
                System.Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

}        


二:集合继承关系,经常会当做

IEnumerable和IEnumerable<T>接口在.NET中是非常重要的接口,它允许开发人员定义foreach语句功能的实现并支持非泛型方法的简单的迭代,IEnumerable和IEnumerable<T>接口是.NET Framework中最基本的集合访问器。它定义了一组扩展方法,用来对数据集合中的元素进行遍历、过滤、排序、搜索等操作。

IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。

IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。

 

一、IEnumerable、IEnumerator、ICollection、IList、List

 

IEnumerator:提供在普通集合中遍历的接口,有Current,MoveNext(),Reset(),其中Current返回的是object类型。
IEnumerable: 暴露一个IEnumerator,支持在普通集合中的遍历。


IEnumerator<T>:继承自IEnumerator,有Current属性,返回的是T类型。
IEnumerable<T>:继承自IEnumerable,暴露一个IEnumerator<T>,支持在泛型集合中遍历。

 

1、IEnumerable接口
 
C# 代码    复制

    // 摘要:
    //     公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代。
    //
    // 类型参数:
    //   T:
    //     要枚举的对象的类型。
    [TypeDependency("System.SZArrayHelper")]
    public interface IEnumerable<out T> : IEnumerable
    {
        // 摘要:
        //     返回一个循环访问集合的枚举器。
        //
        // 返回结果:
        //     可用于循环访问集合的 System.Collections.Generic.IEnumerator<T>。
        IEnumerator<T> GetEnumerator();
    }

 

可以看到,GetEnumerator方法返回对另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,调用方可以用来移动IEnumerable兼容容器包含的内部对象。

 

2、IEnumerator接口

 
C# 代码    复制

public interface IEnumerator

{

  bool MoveNext(); //将游标的内部位置向前移动

  object Current{get;} //获取当前的项(只读属性)

  void Reset(); //将游标重置到第一个成员前面

}

 

 3、ICollection接口:ICollection<T> 同时继承IEnumerable<T>和IEnumerable两个接口

 
C# 代码    复制

    // 摘要:
    //     定义操作泛型集合的方法。
    //
    // 类型参数:
    //   T:
    //     集合中元素的类型。
    [TypeDependency("System.SZArrayHelper")]
    public interface ICollection<T> : IEnumerable<T>, IEnumerable

 

4、IList接口

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

 

5、List的定义

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

 

 

二、IEnumerable实例

 
C# 代码   复制

using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Text;
 
using System.Collections;
 
namespace IEnumeratorSample
 
{
 
    class Person : IEnumerable
 
    {
 
        public string Name;//定义Person的名字
 
        public string Age;//定义Person的年龄
 
        public Person(string name, string age)//为Person初始化(构造函数)
 
        {
 
            Name = name;//配置Name值
 
            Age = age;
 
        }
 
        private Person[] per;
 
        public Person(Person[] array)//重载构造函数,迭代对象
 
        {
 
            per = new Person[array.Length];//创建对象
 
            for (int i = 0; i < array.Length; i++)//遍历初始化对象
 
            {   per[i] = array[i];//数组赋值   }
 
        }
 
        public IEnumerator GetEnumerator()//实现接口
 
        {
 
            return new PersonEnum(per);
 
        }
 
    }
 
    class PersonEnum : IEnumerator//实现foreach语句内部,并派生
 
    {
 
        public Person[] _per;//实现数组
 
        int position = -1;//设置“指针”
 
        public PersonEnum(Person[] list)
 
        {
 
            _per = list;//实现list
 
        }
 
        public bool MoveNext()//实现向前移动
 
        {
 
            position++;//位置增加
 
            return (position < _per.Length);//返回布尔值
 
        }
 
 
 
        public void Reset()//位置重置
 
        {
 
 
 
            position = -1;//重置指针为-1
 
        }
 
        public object Current//实现接口方法
 
        {
 
            get
 
            {   try   {   return _per[position];//返回对象   }   catch (IndexOutOfRangeException)//捕获异常   {   throw new InvalidOperationException();//抛出异常信息   }   }
 
        }
 
    }
 
 
    class Program
 
    {
 
 
 
        static void Main(string[] args)
 
        {
 
            Person[] per = new Person[2] 

            {   new Person("guojing","21"),   new Person("muqing","21"),   };
 
            Person personlist = new Person(per);
 
            foreach (Person p in personlist)//遍历对象
 
            {     Console.WriteLine("Name is " + p.Name + " and Age is " + p.Age);     }
 
            Console.ReadKey();
 
        }
 
    }
 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值