【发布时间】:2014-06-15 21:11:07
【问题描述】:
是否存在制作短代码,我可以替换 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 进行比较。
【问题讨论】:
标签: c# wpf variables int compare
是否存在制作短代码,我可以替换 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 进行比较。
【问题讨论】:
标签: c# wpf variables int compare
您可以将可能的数字放在一个数组中,然后像这样进行比较:
int x = 1;
int[] compareArray = new[] { 1, 3, 12, 33 };
if (compareArray.Contains(x))
{
//condition met
}
或者你可以使用Enumerable.Any 喜欢:
if (compareArray.Any(r=> r == x))
【讨论】:
if (x.EqualsAny(1, 3, 12, 33))
public static bool EqualsAny(int number, params int[] array){ return array.Contains(number);} 这样的静态方法可能会完成这项工作。可以叫MyClass.EqualsAny(x, 1, 3, 4, 5);
您可以使用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;
}
【讨论】:
迟到了,我肯定会肯定建议使用一个简单的解决方案,例如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 检查和if 语句的最终true/false 评估。
这两个类一起工作使得语法 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
【讨论】: