简体   繁体   中英

Detect if result is 0 , -4 or something else?

I have a method which has result at the end,I would want to detect if number is not 0 and if it's -4. 0 Means good -4 Means something that can be solve And anything else is bad. Like

if ( Result != 0)
{
MessageBox.Show("It's bad!")
}
else if ( Result == -4)
{
Thread.Sleep(20000);
MyMethod.TryAgain();
}
else
{
MessageBox.Show("It's good");
}

My problem is that -4 is not 0,so if i get result -4 it takes my Result != 0 method. How can I solve it? Thank you in advance.

Use switch and case .

switch (Result) {
    case 0: 
        MessageBox.Show("It's good"); 
        break;
    case -4: 
        Thread.Sleep(20000);
        MyMethod.TryAgain();
        break;
    default:
        MessageBox.Show("It's bad!");
        break;
}

Microsoft documentation: https://msdn.microsoft.com/en-us/library/06tc147t(v=vs.110).aspx

Just reorder your if-structure to the following:

if ( Result == 0)
{
    MessageBox.Show("It's good")
}
else if ( Result == -4)
{
    Thread.Sleep(20000);
    MyMethod.TryAgain();
}
else
{
    MessageBox.Show("It's bad");
}

So your initial problem, that the Result != 0 case is evaluated first, is gone.

When you are building a chain of non-exclusive conditions, start with the strongest one (ie the most specific condition). Otherwise the code for the weaker condition will execute, blocking access to more specific ones.

In your case, Result == -4 implies that Result != 0 , meaning that the first condition is more specific than the second one. Hence you should check Result == -4 before Result != 0 . Otherwise, Result == -4 would never be reached.

C# offers multiple ways of implementing this logic. As long as you follow a general rule of ordering your conditionals from most specific to least specific, picking a particular implementation is up to you.

Simply change order of branches

if (Result == -4) \\ solve
else if (Result != 0) \\ bad
else \\ good

Sorry, wrong code. See comment below.

switch(Result) {
case 0:
  MessageBox.Show("It's bad!");
  break;
case -4:
  Thread.Sleep(20000);
  MyMethod.TryAgain();
  break;
default:
  MessageBox.Show("It's good");
  break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM