Evaluate Expressions in Switch Statements in C#

前端 未结 12 485
抹茶落季
抹茶落季 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条回答
  •  旧时难觅i
    2021-01-31 02:25

    In twist of C# fate, this has come all the way back around. If you upgrade to C# 9.0, your original switch statement will now compile! C#9.0 has added Relational patterns to pattern matching in general, which includes switch statements.

    You can now do some really funky stuff, like this:

          var num = new Random().Next();
          
          switch(num)
          {
            case < 0:
              // some code ;
              break;
            case 0:
              // some code ;
              break;
            case > 0 and < 10:
              // some code ;
              break;
            case > 20 or (< 20 and 15):
              // some code ;
              break;
          }
    

    Note the use of literal 'and' and 'or' in the last case, to allow && and || type expressions to compile.

    To use C# 9, make sure the XmlNode LangVersion is set to Latest or 9.0 in the csproj file, in a property group

    e.g.

      
        netstandard2.0
        AnyCPU;x86
        Debug;Release;Mock
        Latest
      
    

提交回复
热议问题