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

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

    Thanks to everybody for your answers and feedback. I was surprised to get so many of them. Looking at them and using some of the ideas, I came up with this solution, which works best for me:

    public static class Extensions
    {
    
        public static T Next(this T src) where T : struct
        {
            if (!typeof(T).IsEnum) throw new ArgumentException(String.Format("Argument {0} is not an Enum", typeof(T).FullName));
    
            T[] Arr = (T[])Enum.GetValues(src.GetType());
            int j = Array.IndexOf(Arr, src) + 1;
            return (Arr.Length==j) ? Arr[0] : Arr[j];            
        }
    }
    

    The beauty of this approach, that it is simple and universal to use. Implemented as generic extension method, you can call it on any enum this way:

    return eRat.B.Next();
    

    Notice, I am using generalized extension method, thus I don't need to specify type upon call, just .Next().

提交回复
热议问题