Evaluate Expressions in Switch Statements in C#

前端 未结 12 459
抹茶落季
抹茶落季 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:13

    Note: the answer below was written in 2009. Switch patterns were introduced in C# 7.


    You can't - switch/case is only for individual values. If you want to specify conditions, you need an "if":

    if (num < 0)
    {
        ...
    }
    else
    {
        switch(num)
        {
            case 0: // Code
            case 1: // Code
            case 2: // Code
            ...
        }
    }
    
    0 讨论(0)
  • 2021-01-31 02:14

    The other way around would be possible also (relating to Jon Skeet's answer):

    switch(num)
    {
      case a:
          break;
      default:
          if( num < 0 )
          {}
       break;
    }
    
    0 讨论(0)
  • 2021-01-31 02:16

    You will have to use if, wether you want or not. Switch is only capable of comparing your value to constant values.

    0 讨论(0)
  • 2021-01-31 02:23

    If your num can't be less than zero:

    public int GetSwitch(int num) { return num < 0 ? -1 : num; }
    switch(GetSwitch(num))
    {
    case 4: // some code ; break;
    case 3:// some code ; break;
    case 0: // some code ; break;
    case -1 :// some code ; break;
    }
    

    If it can, use some other "non-existent" number such as int.MinValue.

    0 讨论(0)
  • 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.

      <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
        <Platforms>AnyCPU;x86</Platforms>
        <Configurations>Debug;Release;Mock</Configurations>
        <LangVersion>Latest</LangVersion>
      </PropertyGroup>
    
    0 讨论(0)
  • 2021-01-31 02:26

    What you could do is to use a delegate like this.

            var actionSwitch = new Dictionary<Func<int, bool>, Action>
            {
                 { x => x < 0 ,     () => Log.Information("less than zero!")},
                 { x => x == 1,     () => Log.Information("1")},
                 { x => x == 2,     () => Log.Information("2")},
                 { x => x == 3,     () => Log.Information("3")},
                 { x => x == 4,     () => Log.Information("4")},
                 { x => x == 5,     () => Log.Information("5")},
            };
    
            int numberToCheck = 1;
    
            //Used like this
            actionSwitch.FirstOrDefault(sw => sw.Key(numberToCheck)).Value();
    

    Just swap out what you wan´t to perform where the Log.Information("x") is and you have your "switch" statement.

    You will need to some error handling if you check for a key that is "found" by the Func.

    If you like to see the Func version of the switch I just wrote a blog post with Switch example chapter.

    But if you can use C# 7 it will give you better switch capabilities.

    0 讨论(0)
提交回复
热议问题