【问题标题】:Get next enum based on the order they are rather than name or value?根据它们的顺序而不是名称或值获取下一个枚举?
【发布时间】:2015-03-19 21:20:22
【问题描述】:

假设我有一个像这样的enum

public enum Something
{
    This = 10,
    That = 5,
    It = 11
}

我想知道是否有可能根据它们的顺序而不是它们的值或名称来获得下一个enum

不幸的是我无法控制数字,我只能更改名称。

例如,如果我有That,那么下一个是It 而不是This

伪代码:

var current = Something.That;
Console.WriteLine(current);
// prints That
current = GetNextEnum(Something.That);
// prints It
Console.WriteLine(current);
current = GetNextEnum(Something.It);
// prints This
Console.WriteLine(current);
// And so the cycle continues...

有什么办法可以做到吗?


更新:

每个脉冲我不能执行多个状态,所以我需要知道我跑过哪个状态才能知道接下来要运行哪个状态,例如:

private Something _state = Something.That;
private void Pulse()
{
   // this will run every pulse the application does
   foreach (var item in (Something)Enum.GetValues(typeof(Something)))
   {
       if (_state == item)
       {
           // Do some stuff here
       }
       _state = next item;
       return;
   }
}

我还试图避免为每个状态创建一个块,而是让状态动态执行,因为它们可以添加或删除。

所以我真正的问题是我怎么知道接下来会发生什么以及我在哪里。

【问题讨论】:

  • 使用List<Something>,那么您就有了真正的订单。
  • 这是一个可能对link有帮助的线程
  • 据我所知,答案是否定的。
  • @TimSchmelter 看到更新
  • 把它们按它们运行的​​数字顺序排列,然后加一个?

标签: c# enums


【解决方案1】:
public Something GetNextEnum(Something e)
{
  switch(e)
  {
     case This:
       return That;
     case That:
       return It;
     case It:
       return This;
     default:
       throw new IndexOutOfRangeException();
  }
}

或者让它成为一个扩展:

public static class MySomethingExtensions {
    public static Something GetNextEnum(this Something e)
    {
      switch(e)
      {
         case This:
           return That;
         case That:
           return It;
         case It:
           return This;
         default:
           throw new IndexOutOfRangeException();
      }
    }
}

你可以这样使用它:

_status=_status.GetNextEnum();

【讨论】:

  • 为什么投反对票?如果您有更好的解决方案,请发布。
  • 我不是反对者,但我怀疑这是因为 OP 希望值循环,即This => That => It => This,等
猜你喜欢
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多