IEnumerable接口

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值