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

后端 未结 24 2004
深忆病人
深忆病人 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:13

    I tried the first solution but it did not work for me. Below is my solution:

        public  object NextEnumItem(object currentEnumItem) 
        {
            if (!currentEnumItem.GetType().IsEnum) throw new 
                    ArgumentException(String.Format("Argument is not an Enum"));
            Array Arr = Enum.GetValues(currentEnumItem.GetType());
            int j = Array.IndexOf(Arr,currentEnumItem) + 1;
            return (Arr.Length == j) ? currentEnumItem : Arr.GetValue(j);
        }
    
        public object PreviousEnumItem(object currentEnumItem)
        {
            if (!currentEnumItem.GetType().IsEnum)
                throw new ArgumentException(String.Format("Argument is not an Enum"));
            Array Arr = Enum.GetValues(currentEnumItem.GetType());
            int j = Array.IndexOf(Arr, currentEnumItem) - 1;
            return (j==-1) ? currentEnumItem : Arr.GetValue(j);
        }
    

提交回复
热议问题