故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

IEnumerable与IEnumerator区别

3484人阅读 2016/12/20 10:11 总访问:3840452 评论:0 收藏:0 手机
分类: .NET



IEnumerable:可枚举。

IEnumerator:一种枚举方案。

如果你想使用枚举,就必须实现接口IEnumerable的方法GetEnumerator(),但是这个方法

返回类型是IEnumerator,他才是真正的实现枚举的功臣,因此要枚举的容器就必须实现

IEnumerator的方法和属性。IEnumerator object具体实现了iterator(通过MoveNext(),Reset(),Current)。

微软官方的一个例子:

using System;
using System.Collections;

public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string 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;

    // 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
    {
        get
        {
            return Current;
        }
    }

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

class App
{
    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);

    }
}


People 实现 IEnumerable ,说明People是可以枚举的,但是怎么枚举呢?

PeopleEnum 实现 IEnumerator ,真正的实现了枚举。他们通过GetEnumerator建立联系。



欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价