什么是简短(和可读!)的方式来确保条件符合条件:
If a is true, then run code.
If b is true, then run code.
If both a and b is true, then do NOT run code.
一种方法是嵌套:
if (a || b)
{
if(!(a && b))
{
//Code
}
}
Run Code Online (Sandbox Code Playgroud)
这很冗长,但也许更容易传达意图?
我们可以通过以下方式缩短它:
if((a||b) && (!a&&b))
Run Code Online (Sandbox Code Playgroud)
但这有点神秘,特别是如果变量名称很长.
我错过了什么吗?有没有更好的方法来写上面的?
您可以像其他人建议的那样使用^,但要小心,因为它也是一个按位排他或.关于它何时用于按位以及何时用于逻辑的确切行为因语言和数据类型而异.
例如在Java中确保A和B是布尔类型,你会没事的.
但是,如果你做的是int i
,那么j
;
if (i ^ j) {
}
Run Code Online (Sandbox Code Playgroud)
然后它将在i和j上执行按位xor,然后如果结果为0,则结果将被处理为false,否则为true.
在Java中,由于表达式的结果不是布尔值,因此会出现语法错误.
一些有效的替代方案:
C/C++:
(!i ^ !j)
// The ! converts i to boolean.
// It also negates the value but you don't need to reverse it back as you are comparing the relative values
Run Code Online (Sandbox Code Playgroud)
C#/ Java的:
(A ^ B)
// Make sure A or B are boolean expressions, you will get a compile time error if they are not though.
Run Code Online (Sandbox Code Playgroud)