是否存在可以替换if()参数的短代码,例如:
int x = 1; // x can be 1,2,3 etc.
if(x==1 || x==3 || x==12)
{
//do something..
}
我不想重复x == 1,x == 3等,只是将数字与x进行比较。
答案 0 :(得分:6)
您可以在数组中包含可能的数字,然后将其比较为:
int x = 1;
int[] compareArray = new[] { 1, 3, 12, 33 };
if (compareArray.Contains(x))
{
//condition met
}
或者您可以使用Enumerable.Any
之类的:
if (compareArray.Any(r=> r == x))
答案 1 :(得分:1)
您可以使用switch
声明相当简洁地执行此操作:
int x= 1;
switch (x)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("x is either 1, 2, 3, or 4");
break
default:
Console.WriteLine("x is not 1, 2, 3, or 4");
break;
}
答案 2 :(得分:0)
晚会,我肯定会肯定建议使用一个简单的解决方案,例如Habib's answer(甚至用扩展方法简化它)。也就是说,我很好奇是否可能以达到Tagon可能一直在寻找的最小语法。也就是说,是否可以有类似的东西:
int x = 1;
if(x == 1 || 3 || 12 || 33)
{
}
我怀疑我在这里使用的一些运算符(以及肯定是一些最佳实践违规)存在不需要的详细程度,但是这样的事情可能会出现运算符重载。结果语法是:
IntComparer x = 1; //notice the usage of IntComparer instead of int
if(x == 1 || 3 || 12 || 33)
{
}
首先,我在比较中有一个“切入点”:
public class IntComparer
{
public int Value { get; private set; }
public IntComparer(int value)
{
this.Value = value;
}
public static implicit operator IntComparer(int value)
{
return new IntComparer(value);
}
public static BoolComparer operator ==(IntComparer comparer, int value)
{
return new BoolComparer(comparer.Value, comparer.Value == value);
}
public static BoolComparer operator !=(IntComparer comparer, int value)
{
return new BoolComparer(comparer.Value, comparer.Value != value);
}
}
这满足了最初的x == 1
检查。从此处开始,它会切换到新类型BoolComparer
:
public class BoolComparer
{
public int Value { get; private set; }
public bool IsSatisfied { get; private set; }
public BoolComparer(int value, bool isSatisfied)
{
this.Value = value;
this.IsSatisfied = isSatisfied;
}
public static bool operator true(BoolComparer comparer)
{
return comparer.IsSatisfied;
}
public static bool operator false(BoolComparer comparer)
{
return !comparer.IsSatisfied;
}
public static implicit operator bool(BoolComparer comparer)
{
return comparer.IsSatisfied;
}
public static BoolComparer operator |(BoolComparer comparer, BoolComparer value)
{
return new BoolComparer(comparer.Value, comparer.Value == value.Value);
}
public static implicit operator BoolComparer(int value)
{
return new BoolComparer(value, false);
}
}
这满足了后续的|| 3 || 12 || 33
检查和true/false
语句的最终if
评估。
这两个类一起工作使得语法tomfoolery工作。 太可怕了。不要使用它。此外,它不适用于否定:if (x != 1 || 3 || 12 || 33)
。这可能是一个简单的解决方案,但我现在不想深入研究这个问题)
一些工作检查:
IntComparer x = 1;
bool check1 = x == 1 || 3 || 12 || 33; //true
bool check2 = x == 2 || 3 || 12 || 33; //false
bool check3 = x == 5 || 1 || Int32.MaxValue; //true
bool check4 = x == -1; //false