2

我试图从一篇MSDN 文章中理解这个例子,根据我对 IEnumberable 接口的理解,我们将能够使用 Foreach 循环遍历类集合,我对 Main 方法感到困惑,我们为什么不使用:

   foreach (Person p in peopleArray)
            Console.WriteLine(p.firstName + " " + p.lastName); 

代替

   People peopleList = new People(peopleArray);
    foreach (Person p in peopleList)
        Console.WriteLine(p.firstName + " " + p.lastName);

例子:

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

    }
}
4

1 回答 1

0

你是对的,你可以简单地使用第一个版本,因为数组实现IEnumerable.

他们选择迭代的原因People仅仅是出于学术目的;演示迭代器如何工作(以及如何实现IEnumerable)。如果他们只是简单地迭代peoplearray,他们将不会使用People该类,这是该示例的主要焦点。

于 2014-02-05T18:40:09.870 回答