开发者

"a constant value is expected" error in switch statement in c#

开发者 https://www.devze.com 2023-03-29 22:25 出处:网络
switch (Rotation.ToString()) { case (-Math.PI / 2).ToSt开发者_C百科ring(): // some code break; } The compiler complains about (-Math.PI / 2).ToString(), \"a constant value is expected\"
switch (Rotation.ToString())
{                  
    case (-Math.PI / 2).ToSt开发者_C百科ring():
    // some code
    break;
}

The compiler complains about (-Math.PI / 2).ToString(), "a constant value is expected" Isn't that a constant?


No method call is a constant value.

Incidentally, since Math.PI is a double, you might want to not use it in "equality" comparisons as you are doing here; there are well-documented pitfalls.

A better approach for a single test would be:

var target = -Math.PI / 2;
if (Math.Abs(Rotation - target) < 0.0001) {
    // some code
}

If there are lots of branches, without going into delegate territory, you can do something like this:

var specialCases = new[] { -Math.PI, -Math.PI / 2 };
var epsilon = 0.001d;
var index = specialCases.Select((d, i) => Math.Abs(Rotation - d) < epsilon ? i : -1)
                        .Where(i => i != -1).DefaultIfEmpty(-1).First();

switch (index) {
    case 0: // -Math.PI
    break;
    case 1: // -Math.PI / 2
    break;
    default: // No match
    break;
}

Not the best use of LINQ, but it will allow you to get back to switch territory with a minimum of tinkering.


Jon answers the gist of the question: the result of a method call is never considered to be a constant from the compiler's perspective. You can do this:

string i = (-Math.PI / 2).ToString();
switch(i)
{
    case "-1.5707963267949": Console.WriteLine("hi");
        break;
}

However, bear in mind that double.ToString() may produce different results depending on the current culture info. (Hence the reason it cannot be constant.) So you're probably better off using the double value directly and, depending on the size of your switch statement, either creating a few if/else statements, or creating a Dictionary keyed on the constant value you're trying to match.

And of course, Jon's initial warning still holds true: while doing floating-point logic, you could very easily end up with a value that should be -pi/2, but which isn't exactly -pi/2, in which case your check will fail. Here be dragons.


Perhaps try:

const var SomeVar = (-Math.PI / 2).ToString();
switch (Rotation.ToString())
{                  
    case SomeVar:
        // some code
    break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消