A或B,不是两者,都不是

时间:2010-07-12 13:46:34

标签: language-agnostic if-statement xor coding-style

自从阅读清洁代码以来,我一直在努力保持代码的描述性和易于理解。我有一个条件,必须填写A或B。但不是两者。而不是。目前,检查此情况的if声明很难一目了然。您将如何编写以下内容以使其一目了然

if ((!string.IsNullOrEmpty(input.A) && !string.IsNullOrEmpty(input.B)) 
    || string.IsNullOrEmpty(input.A) && string.IsNullOrEmpty(input.B))
{
    throw new ArgumentException("Exactly one A *OR* B is required.");
}

8 个答案:

答案 0 :(得分:24)

XOR的时间:

if(!(string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)))
    throw new ArgumentException("Exactly one A *OR* B is required.");

您可能还会将其视为:

if(!(string.IsNullOrEmpty(input.A) ^ string.IsNullOrEmpty(input.B)))
    throw new ArgumentException("Exactly one A *OR* B is required.");

答案 1 :(得分:13)

if (string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)) {
 // do stuff
}

答案 2 :(得分:12)

它是一个XOR,它很容易模仿。

考虑一下:

两者都不可能是真的,两者都不能是假的。一个必须是真的,一个必须是假的。

所以,我们来看看:

if(string.IsNullOrEmpty(input.A) == string.IsNullOrEmpty(input.B)) {
   throw new ArgumentException("Exactly one A *OR* B is required.");
}

如果两者相等,则它们都是真的,或者都是假的。这两种情况都是无效的。

所有没有任何特殊XOR运算符的选择语言可能没有。 ;)

答案 3 :(得分:6)

此关系称为exclusive-or(xor)。

有些语言将其作为运算符提供 - 通常是^:

True ^ True -> False
True ^ False -> True
False ^ True -> True
False ^ False -> False

答案 4 :(得分:3)

使用exclusive-OR:A XOR B

答案 5 :(得分:2)

您正在寻找的是XOR(http://en.wikipedia.org/wiki/Exclusive_or)逻辑。

你可以把它写成:

if (string.IsNullOrEmpty(A) ^ string.IsNullOrEmpty(B))
{
//Either one or the other is true
}
else
{
//Both are true or both are false
}

答案 6 :(得分:1)

您需要的是 XOR,即异或或操作。

真相表会向您显示 ;)

A   B   ⊕
F   F   F
F   T   T
T   F   T
T   T   F

在某些语言(或大多数语言)中,它由 A ^ B 表示。

good wiki article

答案 7 :(得分:0)

这是排他性或。的定义。使用布尔代数有很多种方法,最简单的方法是使用XOR运算符。在C中,虽然没有逻辑xor,但你可以使用二进制文件,将not运算符加倍以强制任何真值为1(如0x01)

!!string.IsNullOrEmpty(input.A) ^ !!string.IsNullOrEmpty(input.B)

或做负面测试

!string.IsNullOrEmpty(input.A) ^ !string.IsNullOrEmpty(input.B)

如果A和B都设置了,那么它们都是真的。