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

时间:2009-05-11 14:49:29

标签: c# switch-statement

这就是我想要做的事情:

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

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

我试过“case:2 || 5”,但它没有用。

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

6 个答案:

答案 0 :(得分:288)

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

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

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

答案 1 :(得分:34)

您可以通过stacking case labels

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

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

答案 2 :(得分:19)

case 2:
case 5:
do something
break;

答案 3 :(得分:17)

如果你没有另外指定(通过写破解),

案例陈述会自动落空。因此你可以写

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

//等......     }

答案 4 :(得分:4)

switch statement的示例显示您无法堆叠非空case,但应使用goto s:

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

答案 5 :(得分:1)

You may do this as of C# 9.0

func createYearDictionary(students: [Student]) -> [Int: [String]] {
    var result = [Int: [String]]()
    for student in students {
        if result[student.yearOfGraduation] == nil {
            result[student.yearOfGraduation] = [student.name]
        } else { 
            result[student.yearOfGraduation]?.append(student.name)
        }
    }
    return result
}