How to get next (or previous) enum value in C#

后端 未结 24 1929
深忆病人
深忆病人 2020-12-04 10:59

I have an enum which is defined like this:

public enum eRat { A = 0, B=3, C=5, D=8 };

So given value eRat.B, I want to get the

24条回答
  •  渐次进展
    2020-12-04 11:39

    For simple solution, you might just extract array from enum.

    eRat[] list = (eRat[])Enum.GetValues(typeof(eRat));
    

    Then you can enumerate

    foreach (eRat item in list)
        //Do something
    

    Or find next item

    int index = Array.IndexOf(list, eRat.B);
    eRat nextItem = list[index + 1];
    

    Storing the array is better than extracting from enum each time you want next value.

    But if you want more beautiful solution, create the class.

    public class EnumEnumerator : IEnumerator, IEnumerable {
        int _index;
        T[] _list;
    
        public EnumEnumerator() {
            if (!typeof(T).IsEnum)
                throw new NotSupportedException();
            _list = (T[])Enum.GetValues(typeof(T));
        }
        public T Current {
            get { return _list[_index]; }
        }
        public bool MoveNext() {
            if (_index + 1 >= _list.Length)
                return false;
            _index++;
            return true;
        }
        public bool MovePrevious() {
            if (_index <= 0)
                return false;
            _index--;
            return true;
        }
        public bool Seek(T item) {
            int i = Array.IndexOf(_list, item);
            if (i >= 0) {
                _index = i;
                return true;
            } else
                return false;
        }
        public void Reset() {
            _index = 0;
        }
        public IEnumerator GetEnumerator() {
            return ((IEnumerable)_list).GetEnumerator();
        }
        void IDisposable.Dispose() { }
        object System.Collections.IEnumerator.Current {
            get { return Current; }
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return _list.GetEnumerator();
        }
    }
    

    Instantiate

    var eRatEnum = new EnumEnumerator();
    

    Iterate

    foreach (eRat item in eRatEnum)
        //Do something
    

    MoveNext

    eRatEnum.Seek(eRat.B);
    eRatEnum.MoveNext();
    eRat nextItem = eRatEnum.Current;
    

提交回复
热议问题