簡體   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