【发布时间】:2011-09-17 10:08:32
【问题描述】:
在 C# 中,不使用 if(index == 7 || index == 8),有没有办法将它们组合起来?我在想if(index == (7, 8))之类的东西。
【问题讨论】:
-
你想完成什么?使其更易于阅读或更简洁?
-
两者。有很多平等条件会占用更多的空间。更紧凑的版本会提供更简洁的代码,而不会失去可读性。
在 C# 中,不使用 if(index == 7 || index == 8),有没有办法将它们组合起来?我在想if(index == (7, 8))之类的东西。
【问题讨论】:
据我所知,在当前的 C# 语法集中,无法组合多个右侧操作数以传递给单个二元运算符。
【讨论】:
没有办法做到这一点,但你当然可以使用if( index >=7 && index <= 8 ) 做一个范围。但是给它一个数字列表将需要您创建一个数组或列表对象,然后使用一种方法来执行此操作。但这只是矫枉过正。
【讨论】:
编写您自己的扩展方法,以便您可以编写
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<int>() { 7, 8 }.Contains(index))
【讨论】:
if (new int[] { 7, 8 }.Contains(index))
if ((new int[]{7,8}).Contains(index))
【讨论】:
int[] 是否可能有不同的答案,但如果使用int 以外的类型,一般来说肯定是可能的)。这只是说,从一个不清楚的问题开始,任何答案都可以说是错误的!
您可以将需要比较的值放入内联数组并使用 Contains 扩展方法。对于初学者,请参阅this article。
几个sn-ps演示了这个概念:
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
【讨论】:
您可以使用扩展方法来完成此操作。
public static bool In<T>(this T obj, params T[] collection) {
return collection.Contains(obj);
}
那么……
if(index.In(7,8))
{
...
}
【讨论】:
switch (GetExpensiveValue())
{
case 7: case 8:
// do work
break;
}
这显然需要更多的代码,但它可以让您免于多次评估函数。
【讨论】:
你需要这样的东西吗
int x = 5;
if((new int[]{5,6}).Contains(x))
{
Console.WriteLine("true");
}
Console.ReadLine();
【讨论】: