13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

164 CHAPTER 6 Implement<strong>in</strong>g iterators the easy wayInstead, let’s create another class to implement the iterator itself. We’ll use the factthat <strong>in</strong> <strong>C#</strong> a nested type has access to its enclos<strong>in</strong>g type’s private members, whichmeans we can just store a reference to the “parent” IterationSample, along with thestate of how far we’ve gone so far. This is shown <strong>in</strong> list<strong>in</strong>g 6.3.List<strong>in</strong>g 6.3class IterationSampleIterator : IEnumerator{IterationSample parent;<strong>in</strong>t position;}<strong>in</strong>ternal IterationSampleIterator(IterationSample parent){this.parent = parent;position = -1;Starts before}first elementpublic bool MoveNext(){if (position != parent.values.Length){position++;}return position < parent.values.Length;}public object Current{get{if (position==-1 ||position==parent.values.Length){throw new InvalidOperationException();}}}Nested class implement<strong>in</strong>g the collection’s iterator<strong>in</strong>t <strong>in</strong>dex = (position+parent.start<strong>in</strong>gPo<strong>in</strong>t);<strong>in</strong>dex = <strong>in</strong>dex % parent.values.Length;return parent.values[<strong>in</strong>dex];public void Reset(){position = -1;}HDMoves back tobefore first elementWhat a lot of code to perform such a simple task! We remember the orig<strong>in</strong>al collectionof values we’re iterat<strong>in</strong>g over B and keep track of where we would be <strong>in</strong> a simplezero-based array C. To return an element we offset that <strong>in</strong>dex by the start<strong>in</strong>gpo<strong>in</strong>t G. In keep<strong>in</strong>g with the <strong>in</strong>terface, we consider our iterator to start logicallybefore the first element D, so the client will have to call MoveNext before us<strong>in</strong>g theCurrent property for the first time. The conditional <strong>in</strong>crement at E makes the testBRefers tocollection we’reiterat<strong>in</strong>g overCE Incrementsposition if we’restill go<strong>in</strong>gFIndicateshow far we’veiteratedPrevents access beforefirst or after last elementGImplementswraparoundLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!