ZFYCH_Love

Simply but Powerful

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
View Code
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];
        }
    }

    public IEnumerator 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;
    }

    public object 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);

    }
}


上面的代码是msdn中的源码。

经常被问到对IEnumerable和IEnumerator的认识。。。

也一直知道是为了实现迭代、foreach...

那么到底是干什么的呢?

到目前为止,理解到:我定义一个类型(类),实例化了一系列对象,一般情况下,我们会放到一个List<T>里,那么这个集合,是支持foreach操作的。

如果,我是说如果,我们不放在现有的集合里,而是放在一个数组里T[],那么如果我还想迭代之,如何做呢?

答案就是这两个东西:支持在非泛型集合上执行简单迭代。

IEnumerable里就一个方法,返回IEnumerator类型的对象;

public IEnumerator GetEnumerator()

IEnumerator里有三个方法需要实现。

MoveNext

Reset

Current

具体实现,请参考顶部代码,我觉得写得结构非常清晰了。

至于在应用中的具体应用,还没想到场景,希望您不吝赐教。

posted on 2013-04-15 16:22  xiaoyang_  阅读(298)  评论(0编辑  收藏  举报