根据它们的顺序而不是名称或值获取下一个枚举?
Get next enum based on the order they are rather than name or value?
假设我有这样一个 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;
}
}
我也在努力避免为每个状态创建一个块,而是让状态动态执行,因为它们可以添加或删除。
所以我真正的问题是我怎么知道接下来会发生什么以及我在哪里。
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();
假设我有这样一个 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;
}
}
我也在努力避免为每个状态创建一个块,而是让状态动态执行,因为它们可以添加或删除。
所以我真正的问题是我怎么知道接下来会发生什么以及我在哪里。
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();