2013-03-20 49 views
2

我想從MSDN article來理解這個例子,爲了我對IEnumberable接口的理解,我們將能夠使用Foreach循環遍歷類集合,我對Main方法感到困惑,爲什麼不'難道我們只是使用:的C#IEnumerable接口

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

    } 
} 
+0

我沒有看到任何理由有額外的枚舉。你是對的,你可以直接遍歷peopleArray而不是創建IEnumerable的實例。 – Venki 2014-02-04 12:23:12

回答

0

你是對的,你可以簡單地使用第一個版本,因爲數組實現IEnumerable

他們選擇迭代People的原因僅僅是爲了學術目的;演示迭代器如何工作(以及如何實現IEnumerable)。如果他們只重複了peoplearray,他們將不會使用People類,這是該示例的主要焦點。