英文:
Update enum to the next or previous state
问题
以下是您要翻译的内容:
I have an enum type and added two helper functions to set the enum to the next value or previous value but it doesn't seem to update and I do not know why.
My enums are setup like this:
public enum State
{
None = 0,
A = 1,
B = 2,
Complete = 3
}
My helper methods look like this:
public static State Next(this State state) => (State)Math.Clamp((int)state++, (int)State.None, (int)State.Complete);
public static State Prev(this State state) => (State)Math.Clamp((int)state--, (int)State.None, (int)State.Complete);
And I use the functions like this:
print(_state);
_state = _state.Next();
print(_state);
However, the prints give me the same result both times:
A
A
What am I getting wrong here?
英文:
I have an enum type and added two helper functions to set the enum to the next value or previous value but it doesn't seem to update and i do not know why.
My enums are setup like this:
public enum State
{
None = 0,
A = 1,
B = 2,
Complete = 3
}
My helper methods look like this:
public static State Next(this State state) => (State)Math.Clamp((int)state++, (int)State.None, (int)State.Complete);
public static State Prev(this State state) => (State)Math.Clamp((int)state--, (int)State.None, (int)State.Complete);
And i use the functions like this:
print(_state);
_state = _state.Next();
print(_state);
However the prints give me the same result both times:
A
A
What am i getting wrong here?
答案1
得分: 4
以下是翻译好的代码部分:
public static State Next(this State state) => (State)Math.Clamp((int)state + 1, (int)State.None, (int)State.Complete);
public static State Prev(this State state) => (State)Math.Clamp((int)state - 1, (int)State.None, (int)State.Complete);
你的问题是你在使用后缀运算符 (int)state++
和 (int)state--
:
x++ 的结果是 x 操作之前的值。
因此,你将原始的 state
值传递给 Math.Clamp()
,它会相应返回这些值。
演示在 这里。
英文:
Your helper methods should be written as follows:
public static State Next(this State state) => (State)Math.Clamp((int)state + 1, (int)State.None, (int)State.Complete);
public static State Prev(this State state) => (State)Math.Clamp((int)state - 1, (int)State.None, (int)State.Complete);
Your problem was that you were using the postfix operators (int)state++
and (int)state--
:
> The result of x++ is the value of x before the operation.
Thus you were passing the original values of state
into Math.Clamp()
, which it duly returned.
Demo here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论