在C#中组合多个条件表达式

在C#中,而不是if(index == 7 || index == 8) ,有没有办法将它们组合起来? 我在想if(index == (7, 8))

您可以使用扩展方法完成此操作。

 public static bool In(this T obj, params T[] collection) { return collection.Contains(obj); } 

然后…

 if(index.In(7,8)) { ... } 

您可以将需要比较的值放入内联数组中,并使用Contains扩展方法。 首先看这篇文章 。

几个片段展示了这个概念:

 int index = 1; Console.WriteLine("Example 1: ", new int[] { 1, 2, 4 }.Contains(index)); index = 2; Console.WriteLine("Example 2: ", new int[] { 0, 5, 3, 4, 236 }.Contains(index)); 

输出:

 Example 1: True Example 2: False 

编写自己的扩展方法,以便编写

 if (index.Between(7, 8)) {...} 

其中Between定义为:

  public static bool Between (this int a, int x, int y) { return a >= x && a <= y; } 

你可以用这个:

  if (new List() { 7, 8 }.Contains(index)) 
 switch (GetExpensiveValue()) { case 7: case 8: // do work break; } 

这显然需要更多代码,但它可能会使您无法多次评估函数。

在当前的C#语法集中,根据我的知识,无法将多个右侧操作数组合在一起传递给单个二元运算符。

 if ((new int[]{7,8}).Contains(index)) 

无法做到这一点,但你肯定可以使用if( index >=7 && index <= 8 )来做范围。 但是给它一个数字列表需要你创建一个数组或列表对象,然后使用一个方法来做到这一点。 但那只是矫枉过正。

你需要这样的东西吗?

  int x = 5; if((new int[]{5,6}).Contains(x)) { Console.WriteLine("true"); } Console.ReadLine();