IEnumerable、GetEnumerator、IEnumerator之间的…

2018-06-17 19:39:13来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

了解了这些也就明白了遍历的原理,晚安。

  1 using System;
  2 using System.Collections;
  3 
  4 public class Person
  5 {
  6     public Person(string fName, string lName)
  7     {
  8         this.firstName = fName;
  9         this.lastName = lName;
 10     }
 11 
 12     public string firstName;
 13     public string lastName;
 14 }
 15 
 16 public class People : IEnumerable
 17 {
 18     private Person[] _people;
 19     public People(Person[] pArray)
 20     {
 21         _people = new Person[pArray.Length];
 22 
 23         for (int i = 0; i < pArray.Length; i++)
 24         {
 25             _people[i] = pArray[i];
 26         }
 27     }
 28 
 29     IEnumerator IEnumerable.GetEnumerator()
 30     {
 31        return (IEnumerator) GetEnumerator();
 32     }
 33 
 34     public PeopleEnum GetEnumerator()
 35     {
 36         return new PeopleEnum(_people);
 37     }
 38 }
 39 
 40 public class PeopleEnum : IEnumerator
 41 {
 42     public Person[] _people;
 43 
 44     // Enumerators are positioned before the first element
 45     // until the first MoveNext() call.
 46     int position = -1;
 47 
 48     public PeopleEnum(Person[] list)
 49     {
 50         _people = list;
 51     }
 52 
 53     public bool MoveNext()
 54     {
 55         position++;
 56         return (position < _people.Length);
 57     }
 58 
 59     public void Reset()
 60     {
 61         position = -1;
 62     }
 63 
 64     object IEnumerator.Current
 65     {
 66         get
 67         {
 68             return Current;
 69         }
 70     }
 71 
 72     public Person Current
 73     {
 74         get
 75         {
 76             try
 77             {
 78                 return _people[position];
 79             }
 80             catch (IndexOutOfRangeException)
 81             {
 82                 throw new InvalidOperationException();
 83             }
 84         }
 85     }
 86 }
 87 
 88 class App
 89 {
 90     static void Main()
 91     {
 92         Person[] peopleArray = new Person[3]
 93         {
 94             new Person("John", "Smith"),
 95             new Person("Jim", "Johnson"),
 96             new Person("Sue", "Rabon"),
 97         };
 98 
 99         People peopleList = new People(peopleArray);
100         foreach (Person p in peopleList)
101             Console.WriteLine(p.firstName + " " + p.lastName);
102 
103     }
104 }
105 
106 /* This code produces output similar to the following:
107  *
108  * John Smith
109  * Jim Johnson
110  * Sue Rabon
111  *
112  */

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:10个步骤让你成为高效的Web开发者

下一篇:URL编码方法比较