IEnumerable和IEnumerator

其实IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个Current属性,来获取当前集合中的项吧。

MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?


IEnumerable的定义:

public interface IEnumerable
    {
        // 摘要: 
        //     返回一个循环访问集合的枚举数。
        //
        // 返回结果: 
        //     一个可用于循环访问集合的 System.Collections.IEnumerator 对象。
        [DispId(-4)]
        IEnumerator GetEnumerator();
    }

IEnumerator的定义:

namespace System.Collections
{
    // 摘要: 
    //     支持对非泛型集合的简单迭代。
    [ComVisible(true)]
    [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
    public interface IEnumerator
    {
        // 摘要: 
        //     获取集合中的当前元素。
        //
        // 返回结果: 
        //     集合中的当前元素。
        object Current { get; }

        // 摘要: 
        //     将枚举数推进到集合的下一个元素。
        //
        // 返回结果: 
        //     如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
        //
        // 异常: 
        //   System.InvalidOperationException:
        //     在创建了枚举数后集合被修改了。
        bool MoveNext();
        //
        // 摘要: 
        //     将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
        //
        // 异常: 
        //   System.InvalidOperationException:
        //     在创建了枚举数后集合被修改了。
        void Reset();
    }
}

下面是一个简单的Demo

定义Car类

class Car
    {
        public string CarName;
        public int CarAge;
        public Car(string name,int age)
        {
            CarName = name;
            CarAge = age;
        }
    }
定义Garage类

class Garage:IEnumerable
    {
        Car[] carArray=new Car[4];//定义为Car类型的carArry数组
        public Garage()
        {
            carArray[0] = new Car("jj", 23);
            carArray[1] = new Car("qq", 44);
            carArray[2] = new Car("ss", 12);
            carArray[3] = new Car("ff", 43);
        }
        public IEnumerator GetEnumerator()
        {
            return this.carArray.GetEnumerator();
        }
    }

运行程序

namespace IEnum
{
    class Program
    {
        static void Main(string[] args)
        {
            Garage garage = new Garage();
            foreach (Car c in garage)
            {
                Console.WriteLine("{0}已经{1}岁了", c.CarName, c.CarAge);
            }
            Console.ReadLine();
        }
    }
}

这个是定义了类的集合(Car类的集合),只有Garage类继承了IEnumerable的接口,才能读取和获取定义为Car类型的carArry数组.


更多了解点击阅读点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值