obtain generic enumerator from an array

前端 未结 7 1246
感情败类
感情败类 2020-12-08 12:23

In C#, how does one obtain a generic enumerator from a given array?

In the code below, MyArray is an array of MyType objects. I\'d like to

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 13:20

    What you can do, of course, is just implement your own generic enumerator for arrays.

    using System.Collections;
    using System.Collections.Generic;
    
    namespace SomeNamespace
    {
        public class ArrayEnumerator : IEnumerator
        {
            public ArrayEnumerator(T[] arr)
            {
                collection = arr;
                length = arr.Length;
            }
            private readonly T[] collection;
            private int index = -1;
            private readonly int length;
    
            public T Current { get { return collection[index]; } }
    
            object IEnumerator.Current { get { return Current; } }
    
            public bool MoveNext() { index++; return index < length; }
    
            public void Reset() { index = -1; }
    
            public void Dispose() {/* Nothing to dispose. */}
        }
    }
    

    This is more or less equal to the .NET implemenation of SZGenericArrayEnumerator as mentioned by Glenn Slayden. You should of course only do this, is cases where this is worth the effort. In most cases it is not.

提交回复
热议问题