如何在switch语句中添加“或”?


129

这就是我想做的:

switch(myvar)
{
    case: 2 or 5:
    ...
    break;

    case: 7 or 12:
    ...
    break;
    ...
}

我尝试使用“ case:2 || 5”,但是没有用。

目的是不要为不同的值编写相同的代码。


您是什么意思“它没有用”?它会给您语法错误还是逻辑错误?
— 扎克

Answers:





17

如果您不另外指定(通过写中断),则案例陈述会自动消失。为此你可以写

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

//等...}


5
请注意,这仅适用于空情况。实体尸体不会自动掉下去。
— 2009年

4

switch语句的示例表明,您不能堆叠非空cases,但应使用gotos:

// statements_switch.cs
using System;
class SwitchTest 
{
   public static void Main()  
   {
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
      switch(n)       
      {         
         case 1:   
            cost += 25;
            break;                  
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;             
         default:            
            Console.WriteLine("Invalid selection. Please select 1, 2, or3.");            
            break;      
       }
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");
   }
}

-1 msdn链接在页面下方有一个堆叠的示例。在任何情况下,堆积的情况下工作,尤其是在这个问题在规定的目的是为了不写重复的代码,你的情况1和2做
— Gary.Ray

有用的答案作为“ goto case”示例。
— Stef Geysels

我讨厌goto声明这是什么1992?
— 摩西
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.