C#-IEnumerator与IEnumerable

IEnumerable是所有可迭代非范型类的基础接口。IEnumerable包括一个方法GetEnumerator方法,方法返回一个IEnumerator。

IEnumerator是所有非范型迭代器的基础接口。foreach语句隐藏了C#迭代器的复杂实现。推荐使用foreach代替直接操作迭代器。
迭代器可以读取集合中的数据,但是不能从底层修改集合。
初始的时候,迭代器定位在集合的第一个元素前面,在读取Current值之前需要调用一次MoveNext将迭代器驱动到第一个元素的位置。
Current一直返回相同的元素直到调用了MoveNext或者Reset方法。MoveNext将Current推进到下一个元素。
如果MoveNext之后position超出了集合的范围,MoveNext将返回false。
通过调用Reset将Current重置到第一个元素之前。

于是我们不难得出

class Program
    {
        static void Main(string[] args)
        {
            Person[] peopleArray = new Person[3]
            {
                new Person("John","Smith"),
                new Person("Tom","Johnson"),
                new Person("Sue","Robon"),
            };
            People peopleList = new People(peopleArray);
            foreach (Person person in peopleList)
            {
                Console.WriteLine(person.firstName + person.lastName);
            }

            IEnumerator enumerator = peopleList.GetEnumerator();
            while (enumerator.MoveNext())
            {
                Person person = (Person)enumerator.Current;
                Console.WriteLine(person.firstName + person.lastName);
            }
        }
    }

上面两种写法是一样的,foreach是一种语法糖,简化了遍历其中的具体实现。被遍历的类通过实现IEnumerable接口和实现一个IEnumerator枚举器实现遍历功能。

使用实例:

class Program
    {
        static void Main(string[] args)
        {
            Person[] peopleArray = new Person[3]
            {
                new Person("John","Smith"),
                new Person("Tom","Johnson"),
                new Person("Sue","Robon"),
            };
            People peopleList = new People(peopleArray);
            foreach (Person person in peopleList)
            {
                Console.WriteLine(person.firstName + person.lastName);
            }
        }
    }
    public class Person
    {
        public string firstName;
        public string lastName;

        public Person(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = 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;
        int position = -1;
        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

        Object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

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

        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

        public void Reset()
        {
            position = -1;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值