Our collection will
store its values in an array (object[]??”no generics here!), and the collection will have
the interesting feature that you can set its logical ???starting point?????”so if the array had five
elements, you could set the start point to 2, and expect elements 2, 3, 4, 0, and then 1
to be returned. (This constraint prevents us from implementing GetEnumerator by
simply calling the same method on the array itself. That would defeat the purpose of
the exercise.)
To make the class easy to demonstrate, we??™ll provide both the values and the starting
point in the constructor. So, we should be able to write code such as listing 6.1 in
order to iterate over the collection.
163 C# 1: the pain of handwritten iterators
object[] values = {"a", "b", "c", "d", "e"};
IterationSample collection = new IterationSample(values, 3);
foreach (object x in collection)
{
Console.WriteLine (x);
}
Running listing 6.1 should (eventually) produce output of ???d???, ???e???, ???a???, ???b???, and finally
???c??? because we specified a starting point of 3. Now that we know what we need to
achieve, let??™s look at the skeleton of the class as shown in listing 6.2.
using System;
using System.Collections;
public class IterationSample : IEnumerable
{
object[] values;
int startingPoint;
public IterationSample (object[] values, int startingPoint)
{
this.
Pages:
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330