Evaluate Expressions in Switch Statements in C#

前端 未结 12 483
抹茶落季
抹茶落季 2021-01-31 01:42

I have to implement the following in a switch statement:

switch(num)
{
  case 4:
    // some code ;
    break;
  case 3:
    // some code ;
    brea         


        
12条回答
  •  遇见更好的自我
    2021-01-31 02:12

    I've run into the following pattern recently, and while I abhor it, I can't argue that it's not practical:

    switch(0)
    {
      case 0 when x < 0:
        ...
        break;
      case 0 when a > 5 && x == 0:
        ...
        break;
    }
    

    The use of dummy expressions ((0) in the switch, and case 0) is absolutely terrible, and I'd hate for it to become an idiom, but hey - it's concise and very clear. For sure it's not some hack that completely obscures the meaning and needs arcane knowledge, but C# would do well to obviate the need for it. I'd like the following to be legal:

    switch                   // maybe () here, if the grammar would demand
    {
      case when x < 0:       // I like the case to stay
        ...
      case when a > 5 && x == 0:
        ...
    }
    

提交回复
热议问题