How add “or” in switch statements?

后端 未结 6 1759
离开以前
离开以前 2020-12-24 04:22

This is what I want to do:

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

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

I tried wi

相关标签:
6条回答
  • 2020-12-24 04:39

    You may do this as of C# 9.0:

    switch(myvar)
    {
        case 2 or 5:
            // ...
            break;
    
        case 7 or 12:
            // ...
            break;
        // ...
    }
    
    0 讨论(0)
  • 2020-12-24 04:45

    You do it by stacking case labels:

    switch(myvar)
    {
        case 2:
        case 5:
        ...
        break;
    
        case 7: 
        case 12:
        ...
        break;
        ...
    }
    
    0 讨论(0)
  • 2020-12-24 04:45

    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... }

    0 讨论(0)
  • 2020-12-24 04:49

    The example for switch statement shows that you can't stack non-empty cases, but should use 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.");
       }
    }
    
    0 讨论(0)
  • 2020-12-24 04:56

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

    switch(myvar)
    {
        case 2:
        case 5:
        ...
        break;
    
        case 7:
        case 12:
        ...
        break;
        ...
    }
    
    0 讨论(0)
  • 2020-12-24 04:59
    case 2:
    case 5:
    do something
    break;
    
    0 讨论(0)
提交回复
热议问题