获取枚举中的下一个项目,如果last + 1返回第一个

时间:2018-11-08 15:03:52

标签: c# enums

我看到了How to get next (or previous) enum value in C#,想知道如果下一个项目是(last + 1),那是否还可以返回第一个项目。想象一下:

public enum MODE {
    OFF,
    CHANNEL,
    TALKING
}

MODE Mode = MODE.OFF;

Mode = Mode.Next(); // should give me MODE.CHANNEL
Mode = Mode.Next(); // should give me MODE.TALKING
Mode = Mode.Next(); // should give me MODE.OFF

2 个答案:

答案 0 :(得分:2)

胡赛特的答案

中添加模运算

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

代码:

public static class Extensions {
  public static T Next<T>(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<T>(Arr, src) + 1) % Arr.Length; // <- Modulo % Arr.Length added

    return Arr[j];
  }
}

答案 1 :(得分:0)

也许这可能有用:

    static void Main(string[] args)
    {
        MODE Mode = MODE.TALKING; //Whatever value;
        int index = (int)Mode;
        index = ++index % 3;
        Mode = (MODE)index;
        Console.WriteLine("Mode value {0} ; index {1}", Mode, index );
        Console.ReadKey();

    }