13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Real-life example: iterat<strong>in</strong>g over ranges177}}return GetEnumerator();protected abstract T GetNextValue(T current);The code is quite straightforward, due to <strong>C#</strong> 2’s iterator blocks. The type constra<strong>in</strong>t onT B ensures that we’ll be able to compare two values, and we perform an executiontimecheck to prevent a range be<strong>in</strong>g constructed with a lower bound higher than theupper bound C. We still need to work around the problem of implement<strong>in</strong>g bothIEnumerable and IEnumerable by us<strong>in</strong>g explicit <strong>in</strong>terface implementation for thenongeneric type E and expos<strong>in</strong>g the generic <strong>in</strong>terface implementation <strong>in</strong> the moreusual, implicit way D. If you don’t immediately see why this is necessary, look back tothe descriptions <strong>in</strong> sections 2.2.2 and 3.4.3.The actual iteration merely starts with the lower end of the range, and repeatedlyfetches the next value by call<strong>in</strong>g the abstract GetNextValue method F until we’vereached or exceeded the top of the range. If the last value found is <strong>in</strong> the range, weyield that as well. Note that the GetNextValue method shouldn’t need to keep anystate—given one value, it should merely return the next one <strong>in</strong> the range. This is usefulas it means that we should be able to make most of the derived types immutable,which is always nice. It’s easy to derive from Range, and we’ll implement the twoexamples given earlier—a range for dates and times (DateTimeRange) and a rangefor <strong>in</strong>tegers (Int32Range). They’re very short and very similar—list<strong>in</strong>g 6.9 shows bothof them together.F“Steps” fromone value tothe nextList<strong>in</strong>g 6.9Two classes derived from Range, to iterate over dates/times and <strong>in</strong>tegersus<strong>in</strong>g System;public class DateTimeRange : Range{readonly TimeSpan step;public DateTimeRange(DateTime start, DateTime end): this (start, end, TimeSpan.FromDays(1)){ }Usesdefaultsteppublic DateTimeRange(DateTime start,DateTime end,TimeSpan step): base(start, end){this.step = step;}Usesspecifiedstep}protected override DateTime GetNextValue(DateTime current){return current + step;Uses step to}f<strong>in</strong>d next valuepublic class Int32Range : Range{readonly <strong>in</strong>t step;Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!