publicclassPerson{publicPerson(string f,string l){this.FirstName = f;this.LastName = l;}publicstring LastName {get;set;}publicstring FirstName {get;set;}}// Collectio of Person objects.This class implements IEnumrable so that// it can be used with ForEach syntax.publicclassPeople:IEnumerable{private Person[] _people;publicPeople(Person[] pArray){
_people =newPerson[pArray.Length];for(int i=0;i<pArray.Length;i++){
_people[i]= pArray[i];}}// Implement for the GetEnumrator methodIEnumerator IEnumerable.GetEnumerator(){return(IEnumerator)GetEnumerator();}privateIEnumeratorGetEnumerator(){returnnewPeopleEnum(_people);}}// When you impement IEnumerable,you must also implement IEnumratorpublicclassPeopleEnum:IEnumerator{public Person[] _people;// Enumerators are positioned before first element// Until the first MoveNext() calledint position =-1;publicPeopleEnum(Person[] list){
_people = list;}publicobject Current
{get{try{return _people[position];}catch(IndexOutOfRangeException){thrownewInvalidOperationException();}}}publicboolMoveNext(){
position++;return position < _people.Length;}publicvoidReset(){
position =-1;}}publicclassProgram{staticvoidMain(string[] args){
Person[] personArray =newPerson[3]{newPerson("asd","qwe"),newPerson("dfg","dfg"),newPerson("tyu","ghj"),};People people =newPeople(personArray);foreach(Person item in people){
Console.WriteLine($"{item.FirstName}·{item.LastName}");}
Console.ReadKey();}}// 代碼執行結果如下://asd·qwe//dfg·dfg//tyu·ghj