Prev | Current Page 340 | Next

Jon Skeet

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

So x.CompareTo(y) < 0 has the same meaning as x < y, for example.
8 If only real life were as simple as this. We haven??™t had to get project approval and specification sign-off from
a dozen different parties, nor have we had to create a project plan complete with resource requirements.
Beautiful!
176 CHAPTER 6 Implementing iterators the easy way
Listing 6.8 is the complete Range class, although we can??™t quite use it yet as it??™s still
abstract.
using System;
using System.Collections;
using System.Collections.Generic;
public abstract class Range : IEnumerable
where T : IComparable
{
readonly T start;
readonly T end;
public Range(T start, T end)
{
if (start.CompareTo(end) > 0)
{
throw new ArgumentOutOfRangeException();
}
this.start = start;
this.end = end;
}
public T Start
{
get { return start; }
}
public T End
{
get { return end; }
}
public bool Contains(T value)
{
return value.CompareTo(start) >= 0 &&
value.CompareTo(end) <= 0;
}
public IEnumerator GetEnumerator()
{
T value = start;
while (value.CompareTo(end) < 0)
{
yield return value;
value = GetNextValue(value);
}
if (value.CompareTo(end) == 0)
{
yield return value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
Listing 6.8 The abstract Range class allowing flexible iteration over its values
B
Ensures we can
compare values
Prevents
???reversed???
ranges
C
D
Implements
IEnumerable
implicitly
Implements
IEnumerable
explicitly
E
177 Real-life example: iterating over ranges
return GetEnumerator();
}
protected abstract T GetNextValue(T current);
}
The code is quite straightforward, due to C# 2??™s iterator blocks.


Pages:
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352