IEnumerator和IEnumerable区别

IEnumerable接口和IEnumerator接口是.NET中非常重要的接口,二者有何区别?

    1. 简单来说IEnumerable是一个声明式的接口,声明实现该接口的类就是“可迭代的enumerable”,但并没用说明如何实现迭代器(iterator).其代码实现为:

         public interface IEnumerable
         {
                IEnumerator GetEnumerator();
          }
    2. 而IEnumerator接口是实现式接口,它声明实现该接口的类就可以作为一个迭代器iterator.其代码实现为:

        public interface IEnumerator
       {
                object Current { get; }

                bool MoveNext();
                void Reset();
        }

   3.一个collection要支持Foreach进行遍历,就必须实现IEnumerable,并一某种方式返回迭代器对象:IEnumerator.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
             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);
            Console.ReadKey();
        }
    }


public class Person //构造一个Person类
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }


    public string firstName;
    public string lastName;
}




public class People : IEnumerable // People类是Person的集合类
{
    private Person[] _people;
    public People(Person[] pArray)//构造函数中将批量Person对象放入集合类的字段中
    {
        _people = new Person[pArray.Length];


        for (int i = 0; i < pArray.Length; i++)
        {
            _people[i] = pArray[i];
        }
    }


    IEnumerator IEnumerable.GetEnumerator() //实现接口的GetEnumerator方法
    {
        return (IEnumerator)GetEnumerator();
    }


    public PeopleEnum GetEnumerator() //重写接口的GetEnumerator方法,自动调用该函数
    {
        return new PeopleEnum(_people);
    }
}


public class PeopleEnum : IEnumerator //实现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 //IEnumerator接口中的方法必须逐一实现
    {
        get
        {
            return Current;
        }
    }


    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

foreach执行的顺序,foreach (Person p in peopleList),首先程序在peopleList执行public PeopleEnum GetEnumerator()生成一个用来迭代的类。然后执行“in”,在迭代类里面执行public bool MoveNext(),改变迭代类中position的位置。然后跳到执行Person,执行迭代类里面的public Person Current。返回的是当前person对象。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`IEnumerator` 和 `IEnumerable` 两个接口是 C# 中用于实现迭代器的关键接口。 `IEnumerable` 接口有一个方法 `GetEnumerator()`,它返回一个实现了 `IEnumerator` 接口的对象,该对象可以迭代集合中的元素。实现了 `IEnumerable` 接口的类可以使用 `foreach` 循环迭代集合中的元素。 `IEnumerator` 接口定义了三个方法: - `MoveNext()`:将枚举数推进到集合的下一个元素。 - `Reset()`:将枚举数重置为其初始位置,即在集合中第一个元素之前。 - `Current`:获取集合中的当前元素。 `IEnumerator` 接口的实现类需要在 `MoveNext()` 方法中实现迭代器的逻辑,并在 `Current` 属性中返回当前元素的值。 示例代码: ```csharp public class MyCollection : IEnumerable { private int[] array = { 1, 2, 3, 4 }; public IEnumerator GetEnumerator() { return new MyEnumerator(array); } private class MyEnumerator : IEnumerator { private int[] array; private int position = -1; public MyEnumerator(int[] array) { this.array = array; } public bool MoveNext() { position++; return (position < array.Length); } public void Reset() { position = -1; } public object Current { get { try { return array[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } } ``` 上述代码中,`MyCollection` 类实现了 `IEnumerable` 接口,并在 `GetEnumerator()` 方法中返回了一个实现了 `IEnumerator` 接口的对象。`MyEnumerator` 类实现了 `IEnumerator` 接口,并在 `MoveNext()` 方法中实现了迭代器的逻辑,同时在 `Current` 属性中返回当前元素的值。这样,我们就可以通过 `foreach` 循环来迭代 `MyCollection` 类中的元素了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值