IEnumerable、GetEnumerator、IEnumerator之间的关系。

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

1usingSystem;2usingSystem.Collections;34publicclassPerson5{6publicPerson(stringfName,stringlName)7{8this.firstName =fName;9this.lastName =lName;10}1112publicstringfirstName;13publicstringlastName;14}1516publicclassPeople : IEnumerable17{18PRivatePerson[] _people;19publicPeople(Person[] pArray)20{21_people =newPerson[pArray.Length];2223for(inti =0; i < pArray.Length; i++)24{25_people[i] =pArray[i];26}27}2829IEnumerator IEnumerable.GetEnumerator()30{31return(IEnumerator) GetEnumerator();32}3334publicPeopleEnum GetEnumerator()35{36returnnewPeopleEnum(_people);37}38}3940publicclassPeopleEnum : IEnumerator41{42publicPerson[] _people;4344//Enumerators are positioned before the first element45//until the first MoveNext() call.46intposition = -1;4748publicPeopleEnum(Person[] list)49{50_people =list;51}5253publicboolMoveNext()54{55position++;56return(position <_people.Length);57}5859publicvoidReset()60{61position = -1;62}6364objectIEnumerator.Current65{66get67{68returnCurrent;69}70}7172publicPerson Current73{74get75{76try77{78return_people[position];79}80catch(IndexOutOfRangeException)81{82thrownewInvalidOperationException();83}84}85}86}8788classApp89{90staticvoidMain()91{92Person[] peopleArray =newPerson[3]93{94newPerson("John","Smith"),95newPerson("Jim","Johnson"),96newPerson("Sue","Rabon"),97};9899People peopleList =newPeople(peopleArray);100foreach(Person pinpeopleList)101Console.WriteLine(p.firstName +""+p.lastName);102103}104}105106/*This code produces output similar to the following:107*108* John Smith109* Jim Johnson110* Sue Rabon111*112*/

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航