There is a switch block for example:
private int State switch (State) { case -1: какие то операции case 0>: ?????? Swears at more zero, please tell me how to organize.
There is a switch block for example:
private int State switch (State) { case -1: какие то операции case 0>: ?????? Swears at more zero, please tell me how to organize.
Try using int.CompareTo :
int result = State.CompareTo(0); switch (result) { case 1 : //>0 break; default: //все остальное break; } If you are not satisfied with the if statements, I would suggest something like this:
enum ComparisonResult { IS_MINUS_ONE, GREATER_THAN_ZERO, OTHER_CASE } ComparisonResult result = ComparisonResult.OTHER_CASE; result = (state == -1) ? ComparisonResult.IS_MINUS_ONE : result; result = (state > 0) ? ComparisonResult.GREATER_THAN_ZERO : result; switch(result) { case ComparisonResult.IS_MINUS_ONE: // ... case ComparisonResult.GREATER_THAN_ZERO: // ... case ComparisonResult.OTHER_CASE: break; } GreaterThenZero looks much better - SpecterI read somewhere that switch, when the number of cases exceeds 7, is compiled into a dictionary that matches the values of the checked expression to a reference to a place in the executable code. Therefore, in theory, this operator is more efficient than a set of if, if there are many options for the condition, but these options should be constants, since they should all be known at compile time.
If you need to combine switch with other conditions, you can do so
switch (someExpression) { case val1: Do1(); break; case val2: Do2(); break; ... default: if (someExpression2(someExpression)) { Do3(); } break; } Source: https://ru.stackoverflow.com/questions/51153/
All Articles