2014-01-30 259 views
1
switch(code) 
{ 
    case 'A': 
    case 'a': 
     // to do 
    default: 
     // to do 
} 

是否有任何方法可以將兩個「case」語句合併在一起?如何在一個switch語句中合併兩個case語句

+3

C#和C++是不同的語言。你問哪一個? –

+2

'switch(code.ToUpper())'怎麼樣,只是大寫的使用它來處理每個'case'。 – Prix

+0

您只需要'break;''case'和'default' – Habib

回答

8

你只需要break;您當前的代碼,如:

​​3210

,但如果你是比較的大寫和小寫字符,那麼你可以使用char.ToUpperInvariant,然後只大寫字符指定情況:

switch (char.ToUpperInvariant(code)) 
{ 
    case 'A': 
     break; 
    // to do 
    default: 
     // to do 
     break; 
} 
0

http://msdn.microsoft.com/en-us/library/06tc147t.aspx

class Program 
{ 
    static void Main(string[] args) 
    { 
     int switchExpression = 3; 
     switch (switchExpression) 
     { 
      // A switch section can have more than one case label. 
      case 0: 
      case 1: 
       Console.WriteLine("Case 0 or 1"); 
       // Most switch sections contain a jump statement, such as 
       // a break, goto, or return. The end of the statement list 
       // must be unreachable. 
       break; 
      case 2: 
       Console.WriteLine("Case 2"); 
       break; 
       // The following line causes a warning. 
       Console.WriteLine("Unreachable code"); 
      // 7 - 4 in the following line evaluates to 3. 
      case 7 - 4: 
       Console.WriteLine("Case 3"); 
       break; 
      // If the value of switchExpression is not 0, 1, 2, or 3, the 
      // default case is executed. 
      default: 
       Console.WriteLine("Default case (optional)"); 
       // You cannot "fall through" any switch section, including 
       // the last one. 
       break; 
     } 
    } 
} 
0

Switch將針對遇到的每個條件進行評估,直至遇到breakdefault或最終右括號。

即它將執行任何匹配的case語句,直到它遇到這些指令之一。

將所有equivilant組cases組合並在最後合併後添加break

請注意,如果沒有匹配,它將落入default塊。

+0

因此,如果第一條語句是'default',然後是'case's,那麼case將不會被執行? –

+0

Case和Switch語句相當於GOTO標籤,所以如果有任何情況匹配,執行就跳轉到它;如果沒有匹配(並且存在默認值),它將跳轉到默認值。所以不,訂單沒有關係 – davbryn

+0

但是你說過「......將評估每一個遇到的狀況,直到它達到休息,默認......」。所以如果默認是第一個條件,它會停止。 –