今天在编码时,visual studio 通知我我的 switch case 可以优化。但是我拥有的代码与 Visual Studio 从我的 switch 案例生成的代码不会产生相同的结果。
我使用的枚举:
public enum State
{
ExampleA,
ExampleB,
ExampleC
};
Run Code Online (Sandbox Code Playgroud)
以下代码运行后,该值等于 2147483647。
State stateExample = State.ExampleB;
double value;
switch (stateExample)
{
case State.ExampleA:
value = BitConverter.ToSingle(BitConverter.GetBytes((long)2147483646), 0);
break;
case State.ExampleB:
value = BitConverter.ToUInt32(BitConverter.GetBytes((long)2147483647), 0);
break;
case State.ExampleC:
value = BitConverter.ToInt16(BitConverter.GetBytes((long)2147483648), 0);
break;
default:
value = 0;
break;
}
Run Code Online (Sandbox Code Playgroud)
但是当visual studio优化switch case的时候,这个值变成了2147483648。
State stateExample = State.ExampleB;
double value = stateExample switch
{
State.ExampleA => BitConverter.ToSingle(BitConverter.GetBytes((long)2147483646), 0), //Commenting this line results in …Run Code Online (Sandbox Code Playgroud)