【c#】IEnumerable、IEnumerator 迭代器

IEnumerable

public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }

IEnumerable非常简单,就一个GetEnumerator()方法,但是这个方法的返回值却是一个IEnumerator对象,从注释我们可以得知IEnumerable代表继承此接口的类可以获取一个IEnumerator实现枚举这个类中包含的集合中的元素的功能(比如List/ArrayList/Dictionary等继承了IEnumeratble接口的类)

IEnumerator

 public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }

IEnumerator有一个object类型的属性,还有一个返回值为bool值的MoveNext方法和一个无返回值的Reset方法

IEnumerator 与 IEnumerable使用的案例

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dotnetLearn.集合学习
{

    public class MyList : IEnumerable
    {
        public int[] _data = new int[10] { 1, 5, 7, 9, 7, 8, 7, 8, 7, 4 };

        public int this[int index]
        {
            get
            {
                return _data[index];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            Console.WriteLine("foreach调用  GetEnumerator");
            return new MIEnumtor(this);
        }
    }

    public class MIEnumtor : IEnumerator
    {
        private MyList myList;

        private int index;

        public MIEnumtor(MyList my)
        {
            index = -1;
            myList = my;
        }

        public object Current
        {
            get
            {
                Console.WriteLine("foreach调用  Current");
                return myList[index];
            }
        }

        public bool MoveNext()
        {
            Console.WriteLine("foreach调用  MoveNext");
            if (index < myList._data.Length - 1)
            {
                index++;
                return true;
            }
            index = -1;
            return false;
        }

        public void Reset()
        {

        }
    }

    public class IEnumerator01
    {
        public void test()
        {
            MyList my = new MyList();

            foreach (var item in my)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

通过输出结果,我们可以发现,foreach在运行时会先调用MyList的GetIEnumerator函数获取一个MIEnumtor,之后通过循环调用MIEnumtor的MoveNext函数,index后移,更新Current属性,然后返回Current属性,直到MoveNext返回false。

区别

IEnumerable表示一个可枚举的集合,可以用 foreach 循环遍历,用于返回一个 IEnumerator(迭代器) 对象

IEnumerator 当一个类实现 IEnumerator 接口时,它表示该类提供了迭代集合的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值