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

对,错,不在乎

  •  -1
  • starf15h  · 技术社区  · 6 年前

    我想问一下验证逻辑的一些正确实践。

    案例1:需要一个文本字段。

    bool required = true;
    if(!String.IsNullOrEmpty("123") != required)
    {
       //Error
    }
    

    bool required = false;
    if(!String.IsNullOrEmpty("123") != required)
    {
       //Error
    }
    

    案例3:文本字段是可选的

    //this flag will change based on different input fields
    bool required = true; 
    if(required != null && (!String.IsNullOrEmpty(input) != required))
    {
      //Error
    }
    

    我考虑过空值,但我不确定这是否是唯一的方法。 谢谢大家!

    1 回复  |  直到 6 年前
        1
  •  1
  •   thepirat000    6 年前

    我想你在找这样的东西:

    bool? mandatory = null;  // true, false or null for "I don't care"
    if(mandatory.HasValue && string.IsNullOrEmpty(x) == mandatory.Value)
    {
       //Error
    }