在C#中,有没有一种方法将
if(index == 7 || index == 8)
合并? 我想到了这样的写法:if(index == (7, 8))
。if(index == 7 || index == 8)
合并? 我想到了这样的写法:if(index == (7, 8))
。public static bool In<T>(this T obj, params T[] collection) {
return collection.Contains(obj);
}
Then...
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
据我所知,在当前的C#语法集中,没有办法将多个右操作数组合成一个传递给单个二进制运算符。
编写自己的扩展方法,这样您就可以编写
if (index.Between(7, 8)) {...}
where 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))
or
)。 - Anthony Pegramswitch (GetExpensiveValue())
{
case 7: case 8:
// do work
break;
}
if ((new int[]{7,8}).Contains(index))
int
以外的类型,则一般情况下可能会有不同的答案)。这只是想说,从一个不清楚的问题开始,任何答案都可能是错误的! - Rotsor你需要类似这样的东西吗?
int x = 5;
if((new int[]{5,6}).Contains(x))
{
Console.WriteLine("true");
}
Console.ReadLine();
没有直接的方法可以做到这一点,但你可以使用 if( index >=7 && index <= 8 )
来进行范围判断。但如果要给它一个数字列表,你需要创建一个数组或列表对象,然后使用相应的方法来实现。但这有点过度设计了。