Speaking of iterators, we must not be strangers, often using the foreach in this loop is that the C # language has built-in iterator pattern, mainly support for non-generic collection of simple iterative interface Ieumerator and public enumerator IEnumerable. Although built-in, this model also has the need for us to learn.
The code is as follows
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedesign Pattern iterator pattern { Public Abstract classIterator//Abstract iterators { Public Abstract ObjectFirst (); Public Abstract ObjectNext (); Public Abstract ObjectCurrent (); Public Abstract BOOLIsmax (); } Public Abstract classAggregate//abstract objects that are iterated { Public AbstractIterator createiterator (); } Public classAiterator:iterator//Specific iterators { PublicAaggregate ListA =NewAaggregate ();//storing objects that are iterated Private intCurrent=0; PublicAiterator (Aaggregate a)//an object that is bound to be iterated when initialized{ListA=A; } Public Override ObjectFirst ()//get the object for the first iteration { returnlista[0]; } Public Override ObjectNext ()//gets the next object of the current object{ Current++; if(Current <Lista.count ()) { returnLista[current]; } Else { return NULL; } } Public Override ObjectCurrent ()//get Current Object { returnLista[current]; } Public Override BOOLIsmax () {returnCurrent = = Lista.count ()?true:false; } } Public classAaggregate:aggregate//the specific iterated object, the iterative direction is forward. { Publicilist<Object> lists =Newlist<Object>(); Public OverrideIterator Createiterator ()//an iterative device for creating iterative objects { return NewAiterator ( This); } Public intCount ()//get the number of iterated objects { returnlists. Count; } Public Object This[intIndex//Indexer { Get { returnLists[index]; } Set{lists. Insert (index, value); } } } Public classBiterator:iterator { PublicAaggregate blist =Newaaggregate (); Private intCurrent=0; PublicBiterator (Aaggregate a) {blist=A; Current= A.count ()-1; } Public Override ObjectCurrent () {returnBlist[current]; } Public Override ObjectFirst () {returnBlist[blist. Count ()-1]; } Public Override BOOLIsmax () {returncurrent<0?true:false; } Public Override ObjectNext () { current--; if(current>=0) { returnBlist[current]; } return NULL; } } classProgram {Static voidMain (string[] args) {Aaggregate a=Newaaggregate (); a[0] ="Hello"; a[1] ="Are you really okay? "; a[2] ="you're a bloody sick man! Lao Tzu is good."; Aiterator b=NewAiterator (a); while(!B.ismax ()) {Console.WriteLine (B.current ()); B.next (); } Console.WriteLine (); Biterator C=NewBiterator (a); while(!C.ismax ()) {Console.WriteLine (C.current ()); C.next (); } console.read (); } }}
Operation Result:
Design Pattern iterator mode