int a = 1, b, c, d;
if(a > 0 || b > 1 || c > 2 || d > 3)
{
//do stuff
}
现在在这种情况下,使 if 正确的是a。那么如何验证这一点呢?
基本上你可以将它们放在 4 个不同的 if 中,但是如果你必须为每个 if 执行重复的代码,你可能会想出一些方法来实现,但实际上是否有一种方法可以传递一些值?
当您不仅需要了解总体结果,还需要了解产生结果的项目时,这是一种方法true, 是将条件放入数组中,并执行 OR 链||你自己:
var conditions = new[] {a > 0, b > 1, c > 2, d > 3};
var whichOne = Array.IndexOf(conditions, true);
if (whichOne >= 0) {
Console.WriteLine("Condition number {0} is true", whichOne);
} else {
Console.WriteLine("The condition is false");
}