C#. Do if( a == (b or c or d)). Is it possible?

前端 未结 11 1898
无人及你
无人及你 2021-02-02 09:31

Is there another way to write something like this:

if (a == x || a == y || a == z)

One way that I found is doing it like this:

         


        
11条回答
  •  忘掉有多难
    2021-02-02 10:05

    Fun fact, as of C#9 this is possible

    var c ='b';
    
    if (c is 'a' or 'b' or 'c')
      Console.WriteLine("yes");
    

    Which compiles to

    if (c == 'a' || c == 'b' || c == 'c')
    {
       Console.WriteLine("yes");
    }
    

    Or you can get more creative

    if (c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '.' or ',')
       Console.WriteLine("yes");
    

    Which would roughly compile to (according to sharp io)

    if (c >= 'a')
    {
       if (c <= 'z')
       {
          goto IL_0025;
       }
    }
    else if (c >= 'A')
    {
       if (c <= 'Z')
       {
          goto IL_0025;
       }
    }
    else if (c == ',' || c == '.')
    {
       goto IL_0025;
    }
    bool flag = false;
    goto IL_002b;
    IL_0025:
    flag = true;
    goto IL_002b;
    IL_002b:
    if (flag)
    {
       Console.WriteLine("yes");
    }
    

    Or use it in a switch

    switch (c)
    {
       case 'a' or 'b' or 'c':
          Console.WriteLine("yes");
       break;
    }
    

提交回复
热议问题