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

前端 未结 11 1658
无人及你
无人及你 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:19

    Why would you need yet another way? Since it isn't a matter of functionality, I would guess the point is to improve readability. If you have a few variables with meaningful names, it would be more readable to just compare by using ==. If you have more, you can use Contains against a list as in your other sample. Yet another way would be comparing against enum flags:

    [Flags]
    public enum Size
    {
        Small = 1,
        Medium = 2,
        Large = 4
    }
    

    And then to find out if mySize is in Small or Medium:

    selectedSizes = Size.Small | Size.Medium;
    mySize = Size.Small;
    if (mySize & selectedSizes)
    {
      ... 
    }
    

提交回复
热议问题