values = values;
this.startingPoint = startingPoint;
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
As you can see, we haven??™t implemented GetEnumerator yet, but the rest of the code is
ready to go. So, how do we go about implementing GetEnumerator? The first thing to
understand is that we need to store some state somewhere. One important aspect of
the iterator pattern is that we don??™t return all of the data in one go??”the client just
asks for one element at a time. That means we need to keep track of how far we??™ve
already gone through our array.
So, where should this state live? Suppose we tried to put it in the IterationSample
class itself, making that implement IEnumerator as well as IEnumerable. At first sight,
this looks like a good plan??”after all, the data is in the right place, including the starting
point. Our GetEnumerator method could just return this. However, there??™s a big
problem with this approach??”if GetEnumerator is called several times, several independent
iterators should be returned. For instance, we should be able to use two
foreach statements, one inside another, to get all possible pairs of values. That suggests
we need to create a new object each time GetEnumerator is called. We could still
implement the functionality directly within IterationSample, but then we??™d have a
class that didn??™t have a clear single responsibility??”it would be pretty confusing.
Pages:
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331