How would you implement the IEnumerator interface?

前端 未结 5 1323
一生所求
一生所求 2020-12-03 03:58

I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom IEnumerator interface that iterates through t

5条回答
  •  孤城傲影
    2020-12-03 04:23

    Here's an example from the book "Algorithms (4th Edition) by Robert Sedgewick".

    It was written in java and i basically rewrote it in C#.

    public class Stack : IEnumerable
    {
        private T[] array;
    
        public Stack(int n)
        {
            array = new T[n];
        }
    
        public Stack()
        {
            array = new T[16];
        }
    
        public void Push(T item)
        {
            if (Count == array.Length)
            {
                Grow(array.Length * 2);
            }
    
            array[Count++] = item;
        }
    
        public T Pop()
        {
            if (Count == array.Length/4)
            {
                Shrink(array.Length/2);
            }
    
            return array[--Count];
        }
    
        private void Grow(int size)
        {
            var temp = array;
            array = new T[size];
            Array.Copy(temp, array, temp.Length);
        }
    
        private void Shrink(int size)
        {
            Array temp = array;
            array = new T[size];
            Array.Copy(temp,0,array,0,size);
        }
    
        public int Count { get; private set; }
        public IEnumerator GetEnumerator()
        {
            return new ReverseArrayIterator(Count,array);
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    
    
        // IEnumerator implementation
        private class ReverseArrayIterator : IEnumerator
        {
            private int i;
    
            private readonly T[] array;
    
            public ReverseArrayIterator(int count,T[] array)
            {
                i = count;
                this.array = array;
            }
    
            public void Dispose()
            {
    
            }
    
            public bool MoveNext()
            {
                return i > 0;
            }
    
            public void Reset()
            {
    
            }
    
            public T Current { get { return array[--i]; } }
    
            object IEnumerator.Current
            {
                get { return Current; }
            }
        }
    }
    

提交回复
热议问题