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

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

    So, you want to replace a simple, efficent language construct that contains short-circuit optimisations into something much slower that has the potential for throwing exceptions?

    However, if the items you want to compare against are not fixed in quantity, i.e. at run time it could be t,u,v,w,x,y,z,etc..., then the Collection.Contains method is the only option, but then you'd be passing collection objects around rather than individual values and so there's little memory allocation ovrehead.

    If you've got a large number of items to compare 'a' against, but the items are not dynamic at run time then a switch statement might be a better fit.

提交回复
热议问题