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.

Advanced generics91}{}return new Count<strong>in</strong>gEnumerator();IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();}CImplementsIEnumerableexplicitlyclass Count<strong>in</strong>gEnumerator : IEnumerator{<strong>in</strong>t current = -1;public bool MoveNext(){current++;return current < 10;}public <strong>in</strong>t Current{get { return current; }}object IEnumerator.Current{get { return Current; }}public void Reset(){current = -1;}public void Dispose(){}}...Count<strong>in</strong>gEnumerable counter = new Count<strong>in</strong>gEnumerable();foreach (<strong>in</strong>t x <strong>in</strong> counter){Console.WriteL<strong>in</strong>e(x);}DImplementsIEnumerator.CurrentimplicitlyEImplementsIEnumerator.CurrentexplicitlyProves thatenumerabletype worksClearly this isn’t useful <strong>in</strong> terms of the result, but it shows the little hoops you haveto go through <strong>in</strong> order to implement generic enumeration appropriately—at least ifyou’re do<strong>in</strong>g it all longhand. (And that’s without mak<strong>in</strong>g an effort to throw exceptionsif Current is accessed at an <strong>in</strong>appropriate time.) If you th<strong>in</strong>k that list<strong>in</strong>g 3.9looks like a lot of work just to pr<strong>in</strong>t out the numbers 0 to 9, I can’t help but agreewith you—and there’d be even more code if we wanted to iterate through anyth<strong>in</strong>guseful. Fortunately we’ll see <strong>in</strong> chapter 6 that <strong>C#</strong> 2 takes a large amount of the workaway from enumerators <strong>in</strong> many cases. I’ve shown the “full” version so you canappreciate the slight wr<strong>in</strong>kles that have been <strong>in</strong>troduced by the design decision forIEnumerable to extend IEnumerable.FLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!