And*_*rew 23 c# conditional-statements
在C#中,if(index == 7 || index == 8)
有没有办法将它们组合起来?我在想类似的东西if(index == (7, 8))
.
48k*_*ocs 55
您可以使用扩展方法完成此操作.
public static bool In<T>(this T obj, params T[] collection) {
return collection.Contains(obj);
}
Run Code Online (Sandbox Code Playgroud)
然后...
if(index.In(7,8))
{
...
}
Run Code Online (Sandbox Code Playgroud)
您可以将需要比较的值放入内联数组中,并使用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));
Run Code Online (Sandbox Code Playgroud)
输出:
Example 1: True
Example 2: False
Run Code Online (Sandbox Code Playgroud)