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

String.IsNullOrEmpty(myString)Vs myString!=无效的

  •  5
  • Asad  · 技术社区  · 16 年前

    string myString = ""; 
    String.IsNullOrEmpty(myString);
    
    vs
    
    string myString = "";
    if(myString.Length > 0 || myString != null)
    
    vs 
    
    string myString = "";
    if (m.Length > 0 | m != null)
    

    7 回复  |  直到 13 年前
        1
  •  18
  •   Marc Gravell    16 年前

    那么问题的版本是:

    if(myString.Length > 0 || myString != null)
    

    肯定 更糟的是,你应该测试一下 null 第一 (不是第二个)-理想情况下,在 无效的 所以你不想打电话 .Length string.IsNullOrEmpty . 如果愿意的话,您可以编写一个扩展方法,使其不那么冗长(您可以在 价值观)。

    static bool HasValue(this string s) {
        return !string.IsNullOrEmpty(s);
    }
    
        2
  •  4
  •   Skurmedel    16 年前

    配合 string.IsNullOrEmpty(str)

    若你们只需要检查字符串“空”,那个么我会检查 string.Empty 因为它更能表达你的意图。

        3
  •  2
  •   Fortyrunner    16 年前

    当您稍后查看代码时,解析将更容易。

    这是另一个有点奇怪的原因。一些后来的程序员肯定会在稍后出现,搔搔他的胡子说“我认为myString.trim().Length!”“0更好”并更改它。

    正如其他人所指出的:检查空秒是一个潜在的空访问错误,等待发生-库例程保证是正常的。

        4
  •  2
  •   ladenedge    16 年前

    Eric Gunnerson's comments ).

    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
        if (value != null)
        {
            return (value.Length == 0);
        }
        return true;
    }
    

        5
  •  1
  •   Guffa    16 年前

    String.IsNullOrEmpty 如果您不确定如何测试字符串引用的不同状态(显然是这样,因为您弄错了…;),则最好选择。

    IsNullOrEmpty 方法:

    if (String.IsNullOrEmpty(s)) ...
    

    等效于对零长度和零长度进行短路测试:

    if (s == null || s.Length == 0) ...
    

    if (s.Length == 0) ...
    

    这个 是空的吗 是空的吗

        6
  •  0
  •   Blade3    16 年前

    我相信String.IsNullOrEmpty(String s)的实现方式如下:

    如果(s==null | | s.Length==0)。。。

        7
  •  -3
  •   Inacss    14 年前

    I believe the String.IsNullOrEmpty(String s) is implemented as: if (s == null || s.Length == 0) ... in the API.

    那是错误的。尝试它,您将得到一个异常,因为这两个语句将被尝试。如果s为null,则s.Length将抛出一个execption。