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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/848472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:03:26  来源:igfitidea点击:

How add "or" in switch statements?

c#switch-statement

提问by Ivan Prodanov

This is what I want to do:

这就是我想要做的:

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

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

I tried with "case: 2 || 5" ,but it didn't work.

我试过 "case: 2 || 5" ,但没有用。

The purpose is to not write same code for different values.

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

采纳答案by Jose Basilio

By stacking each switch case, you achieve the OR condition.

通过堆叠每个开关案例,您可以实现 OR 条件。

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

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

回答by On Freund

case 2:
case 5:
do something
break;

回答by Dave Webb

You do it by stacking case labels:

您可以通过堆叠案例标签来实现

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

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

回答by AnnaR

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

如果您没有另外指定(通过写中断),案例陈述会自动失败。因此你可以写

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

// etc... }

// 等等... }

回答by gimel

The example for switch statementshows that you can't stack non-empty cases, but should use gotos:

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.");
   }
}