首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

並發事件:透過 C# 簡化 APM (5) — 迭代器 ArrayEnumerator/ArrayEnumerable/ArrayIterator 完整程式碼

     編輯:關於C語言

Figure 3:迭代器完整實作


private static void Iterators() {
    Int32[] numbers = new Int32[] { 1, 2, 3 };
    foreach (Int32 num in numbers) Console.WriteLine(num);
    foreach (Int32 num in new ArrayEnumerable<Int32>(numbers)) Console.WriteLine(num);
    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);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved