将枚举更新到下一个或前一个状态。

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 08:14:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定