Figure3迭代器
private static void Iterators() {
Int32[] numbers = new Int32[] { 1, 2, 3 };
// Use Array's built-in IEnumerable
foreach (Int32 num in numbers)
Console.WriteLine(num);
// Use my ArrayEnumerable class
foreach (Int32 num in new ArrayEnumerable<Int32>(numbers))
Console.WriteLine(num);
// Use my iterator
foreach (Int32 num in ArrayIterator(numbers))
Console.WriteLine(num);
}
private sealed class ArrayEnumerator<T>: IEnumerator<T> {
private T[] m_array;
private Int32 m_index;
public ArrayEnumerator(T[] array) {
m_array = array; m_index = array.Length;
}
public Boolean MoveNext() {
if (m_index == 0) return false;
m_index--; return true;
}
public T Current { get { return m_array[m_index]; } }
Object IEnumerator.Current { get { return Current; } }
public void Dispose() { }
public void Reset() { }
}
private sealed class ArrayEnumerable<T>: IEnumerable<T> {
private T[] m_array;
public ArrayEnumerable(T[] array) { m_array = array; }
public IEnumerator<T> GetEnumerator() {
return new ArrayEnumerator<T>(m_array);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
private static IEnumerable<T> ArrayIterator<T>(T[] array) {
try { yIEld return default(T); }
finally { }
for (Int32 index = array.Length - 1; index >= 0; index--)
yIEld return array[index];
}
private static IEnumerator<Int32>
ApmPatternWithIterator(AsyncEnumerator ae) {
using (FileStream fs =
new FileStream(typeof(ApmPatterns).Assembly.Location,
FileMode.Open, FileAccess.Read, FileShare.Read, 8192,
FileOptions.Asynchronous)) {
Byte[] data = new Byte[fs.Length];
fs.BeginRead(data, 0, data.Length, ae.End(), null);
yIEld return 1;
Int32 bytesRead = fs.EndRead(ae.DequeueAsyncResult());
ProcessData(data);
}
}