超级怪兽工厂txt下载:[C#]实现IEnumerable接口来使用foreach语句的一个实例

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 00:32:52
实现IEnumerable接口来使用foreach语句的一个实例

 

view sourceprint? 01 using System; 02 using System.Collections.Generic; 03 using System.Linq; 04 using System.Text; 05 using System.Collections; 06    07 namespace IEnumeratorSample 08 { 09     class Person : IEnumerable                         //派生自IEnumerable,同样定义一个Personl类 10     { 11         public string Name; 12         public string Age; 13         public Person(string name, string age) 14         { 15             Name = name; 16             Age = age; 17         } 18    19         private Person[] per; 20         public Person(Person[] array)//重载构造函数,迭代对象,用一个数组来存放Person的集合,在后面用foreach来访问,但是仍然要实现GetEnumerator() 21         { 22             per = new Person[array.Length]; 23    24             for (int i = 0; i < array.Length; i++) 25             { 26                 per[i] = array[i]; 27             } 28         } 29    30         public IEnumerator GetEnumerator()//实现GetEnumerator()接口 31         { 32             return new PersonEnum(per);//在这里调用PersonEnum 33         } 34     } 35    36     class PersonEnum : IEnumerator                    //实现foreach语句内部,并派生 37     { 38         public Person[] _per; 39         int position = -1; 40    41         public PersonEnum(Person[] list) 42         { 43             _per = list; 44         } 45    46         public bool MoveNext() 47         { 48             position++; 49             return (position < _per.Length); 50         } 51    52         public void Reset() 53         { 54             position = -1; 55         } 56    57         public object Current 58         { 59             get 60             { 61                 try 62                 { 63                     return _per[position]; 64                 } 65                 catch (IndexOutOfRangeException) 66                 { 67                     throw new InvalidOperationException(); 68                 } 69             } 70         } 71     } 72    73     class Program 74     { 75         static void Main(string[] args) 76         { 77             Person[] per = new Person[2]                //同样初始化并定义2个Person对象 78             { 79                 new Person("guojing","21"), 80                 new Person("muqing","21"), 81             }; 82    83             Person personlist = new Person(per);            //初始化对象集合 84             foreach (Person p in personlist)                //使用foreach语句 85                 Console.WriteLine("Name is " + p.Name + " and Age is " + p.Age); 86             Console.ReadKey(); 87         } 88     } 89 }