代码之家  ›  专栏  ›  技术社区  ›  CaffGeek

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

  •  9
  • CaffGeek  · 技术社区  · 14 年前

    自从阅读干净的代码,我一直试图保持我的代码描述性和易于理解。我有一个条件,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 回复  |  直到 14 年前
        1
  •  24
  •   Justin Niessner    14 年前

    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.");
    
        2
  •  13
  •   Nordic Mainframe    14 年前
    if (string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)) {
     // do stuff
    }
    
        3
  •  12
  •   Hendrik    14 年前

    它是一个异或,而且非常容易模仿。

    想想看:

    所以,我们得出这样的结论:

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

    如果两者相等,那么它们要么都是真的,要么都是假的。两个案子都是无效的。

    所有这些,如果没有任何特殊的异或运算符,选择的语言可能就没有了

        4
  •  6
  •   Donald Miner    14 年前

    这种关系称为异或(xor)。

    True ^ True -> False
    True ^ False -> True
    False ^ True -> True
    False ^ False -> False
    
        5
  •  3
  •   Mitch Wheat    14 年前
        6
  •  2
  •   Ian Jacobs    14 年前

    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
    }
    
        7
  •  1
  •   Pratik Deoghare    14 年前

    你需要的是 异或,即异或 操作。

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

    在某些语言中(或在大多数语言中)用 一个^B .

    good wiki article

        8
  •  0
  •   falstro    14 年前

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

    或者做阴性测试

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