繁体   English   中英

在开关案例中使用And与多个变量?

[英]use And with multiple variables in switch-case statements?

我有这样的代码:

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

我可以将其转换为switch case语句吗

因为switch只接受一个变量,所以不能。 并且您有两个变量。 不过,您始终可以重构代码。

喜欢:

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

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

//something...

更具可读性(恕我直言)。

编辑

这太疯狂了:),但是由于您的变量是整数,因此您可以将它们组合为一个长变量并使用开关。

喜欢:

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

好吧....如果您必须这样做将可以:警告-密码

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()();

这可能写得更简洁。

它确实取决于更大的图片代码的外观,但是我偶尔使用以下技术。

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

可读性很强,但可能会失控。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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