为什么在这个实例(从msdn),在GetEnumerator方法,新的PeopleEnum返回IEnumerator?

StackOverflow https://stackoverflow.com/questions/2635219

  •  26-09-2019
  •  | 
  •  

为什么在这个例从MSDN, GetEnumerator 方法, PeopleEnum 返回 IEnumerator?

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];
        }
    }
   //why??? 
   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();
        }
    }
}

更新: 顺便说一句,如果阵列数据的类型实现的实际内容接口,为什么msdn已复制到微_people通过编写一个为循环?

有帮助吗?

解决方案

它需要返回 到底 IEnumerator 正确地执行 IEnumerable 接口。它是这样使用"明确的界面执行",因此在 公共 API你看 PeopleEnum, 但 IEnumerable 仍然是高兴

但在现实中你会 非常罕见 写一枚举这种方式在C#2.0或以上;你会用一个迭代块(yield return).看看 C#在深度 第6章(免费的章节!).

对信息的原因 PeopleEnum 存在 在所有 这里是,这看起来像一个.净1.1样,这是唯一的方法,以创建一个类型枚举器。中。网2.0及以上有 IEnumerable<T> / IEnumerator<T>, ,其中有一个输入(通过泛型) .Current.

中。网2.0/C#2.0(或以上),我将简单:

public class People : IEnumerable<Person> {
    /* snip */
    public IEnumerator<Person> GetEnumerator() {
        return ((IEnumerable<Person>)_people).GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator() { return _people.GetEnumerator();}
}

其他提示

类型执行综合需要的方法称为GetEnumerator返回IEnumerator.在这一范例(这是非常过时,因为C#2.0)有一枚举的类PeopleEnum实现IEnumerator.它是什么内部使用的C#foreach发言。

一个最新的例子看起来更像以下。注意到不再需要一PeopleEnum类现在,C#支持迭代器。有效地编译器完成所有的重你。

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()
   {
       for (int i=0; i < _people.Length; i++) {
           yield return _people[i];
       }
   }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top