Prev | Current Page 187 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Of course,
now you need to implement IEnumerator and you quickly run into similar problems,
this time with the Current property.
Listing 3.9 gives a full example, implementing an enumerable class that always just
enumerates to the integers 0 to 9.
class CountingEnumerable: IEnumerable
{
public IEnumerator GetEnumerator()
Listing 3.9 A full generic enumeration??”of the numbers 0 to 9
Implements
IEnumerable
implicitly
B
91 Advanced generics
{
return new CountingEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class CountingEnumerator : IEnumerator
{
int current = -1;
public bool MoveNext()
{
current++;
return current < 10;
}
public int Current
{
get { return current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
current = -1;
}
public void Dispose()
{
}
}
...
CountingEnumerable counter = new CountingEnumerable();
foreach (int x in counter)
{
Console.WriteLine(x);
}
Clearly this isn??™t useful in terms of the result, but it shows the little hoops you have
to go through in order to implement generic enumeration appropriately??”at least if
you??™re doing it all longhand. (And that??™s without making an effort to throw exceptions
if Current is accessed at an inappropriate time.) If you think that listing 3.9
looks like a lot of work just to print out the numbers 0 to 9, I can??™t help but agree
with you??”and there??™d be even more code if we wanted to iterate through anything
useful.


Pages:
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199