简体   繁体   中英

use And with multiple variables in switch-case statements?

I have a code like this :

if(x==1 && y==2){
    something...
    }
    else if(x==4 && y==6){
    something...
    }
    else{
    something...
    }

Can I convert it to a switch case statement

You can't since switch is taking only one variable; and you have two variables. You can always refactor your code a little bit though.

Like:

if (x==1 && y==2) {
  //something...
  return;
}

if (x==4 && y==6) {
  //something...
  return;
}

//something...

Much more readable (imho).

EDIT

This is crazy :) but since your variables are integer you can combine them into one long variable and use the switch.

Like:

switch ((((long)x) << 32) + y) {
  case ((1L << 32) + 2):
    break;
  case ((4L << 32) + 6):
    break;
  default:
    break;
}

Well.... if you have to this would work: WARNING - HACK CODE

int x;
int y;
var @switch= new Dictionary<Func<bool> statement, Action doIfTrue>
{
    {() => x == 1 && y == 2, something},
    {() => x == 4 && y == 6, somethingElse}
    {() => true, () = {} } // fallback action
};

@switch.Where(pair => pair.Key()).Select(pair => pair.Value).First()();

This could probably be written a bit more terse.

It does depend a bit on how the bigger picture code looks, but I've used the following technique occasionally.

switch (x*100+y) {
case 102:
// something...
break;
case 406:
// something...
break;
default:
// something...
}

It's pretty readable, but can get out of hand.

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