First, use an array to iterate,foreach (person p in people. Persons), as follows:
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceienumerabletest{classProgram {Static voidMain (string[] args) {person[] Persons=Newperson[4] { NewPerson ("John","Smith", -,true), NewPerson ("Kite","Green", -,false), NewPerson ("Lei","Li", -,true), NewPerson ("Meimei","Han", the,false) }; People people=Newpeople (persons); foreach(Person Pinchpeople. Persons) {Console.WriteLine (p.tostring ()); } } } Public classpeople {Privateperson[] _persons; Publicperson[] Persons {Get{return_persons;} Set{_persons =value;} } Publicpeople (person[] persons) { This. Persons =persons; } } Public classPerson { PublicPerson (stringFirstName,stringLastName,intAgeBOOLgender) { This. FirstName =FirstName; This. LastName =LastName; This. Age =Age ; This. Gender =gender; } Private string_FirstName; Public stringFirstName {Get{return_FirstName;} Set{_FirstName =value;} } Private string_lastname; Public stringLastName {Get{return_lastname;} Set{_lastname =value;} } Private int_age; Public intAge {Get{return_age;} Set{_age =value;} } Private BOOL_gender; Public BOOLGender {Get{return_gender;} Set{_gender =value;} } Public Override stringToString () {stringGender =string. Empty; if( This. Gender) Gender="male"; ElseGender="female"; return string. Format ("{0} {1}, {2}, is {3} years -old.", This. FirstName, This. LastName, Gender, This. Age); } }}
View Code
Second, because of some necessary reasons, do not want to operate directly outside the class people. Persons, the transformation of class people is as follows:
Public class people { private person[] _persons; Public people (person[] persons) { thisnew person[persons. Length]; for (int0; i < persons. Length; i++) { = persons[i]; }}}
View Code
At this point, the people. It is not possible to traverse the Persons. However, we still have the need to traverse the persons.
What to do? Continue to transform the class peopleso that we can traverse the class people directly:foreach (person p in people)
How to change? Adds an iterator.
Third, add iterators
1. Inheriting IEnumerable
2. Add a method
IEnumerator Ienumerable.getenumerator () { ... }
As follows:
Public classpeople:ienumerable {Privateperson[] _persons; Publicpeople (person[] persons) { This. _persons =Newperson[persons. Length]; for(inti =0; I < persons. Length; i++) {_persons[i]=Persons[i]; }} IEnumerator Ienumerable.getenumerator () {//... } }
View Code
Examples of use of C # iterators