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

if语句中运算符的顺序

  •  3
  • JohnB  · 技术社区  · 14 年前

    我经常在必要时这样做,以防止 空指针异常 :

    // Example #1
    if (cats != null && cats.Count > 0)
    {
      // Do something
    }
    

    在1中,我一直假设 cats != null 必须是第一个,因为操作顺序从左到右进行评估。

    然而, 不像 示例1,如果对象是 null 或者如果 Count 为零,因此我使用的是逻辑或而不是和:

    // Example #2
    if (table == null || table.Rows == null || table.Rows.Count <= 0)
    {
      // Do something
    }
    

    逻辑比较的顺序有关系吗?或者我也可以颠倒顺序并得到相同的结果,比如在示例3中?

    // Example #3
    if (table.Rows.Count <= 0 || table.Rows == null || table == null)
    {
      // Do something
    }
    

    (顺便说一句,我意识到我可以像下面那样重写2,但我认为它很混乱,我仍然对OR运算符很好奇)

    // Example #4
    if (!(table != null && table.Rows != null && table.Rows.Count > 0))
    {
      // Do something
    }
    
    6 回复  |  直到 14 年前
        1
  •  2
  •   Jon Hanna    14 年前

        2
  •  11
  •   Michael Petrotta user3140870    14 年前

    if (table == null || table.Rows == null || table.Rows.Count <= 0)
    {
      // Do something
    }
    

    table.Rows table.Rows.Count tables

    short-circuiting

    bool A()
    {
        return false;
    }
    
    bool B()
    {
        return true;
    }
    
    //...
    
    if (A() && B())
    {
        // do something
    }
    

    A() B()

    ||

        3
  •  2
  •   jnielsen    14 年前

        4
  •  0
  •   Charles Bretana    14 年前

     if (table == null || table.Rows == null || table.Rows.Count <= 0 || ) 
     {}
     else
     { 
      // Do something 
     } 
    

        5
  •  0
  •   Nix    14 年前

    if (null== null || null.Rows == null || null.null.Count <= 0)
    {
      // Do something
    }
    

    if( true || null.Rows == null || null.null.Count <=0)
    

    if (null.null.Count <= 0 || null.Rows == null || null== null)
    {
      // CRASH... Do something
    }
    
        6
  •  -1
  •   user432209    14 年前