为什么要创建string.IsNullOrEmpty()?

Jav*_*ram 7 .net c# string

如果创造了string.Empty != null原因string.IsNullOrEmpty()

我只是想说:
如果nullstring.Empty彼此不同.

  • 为什么string.IsNull();string.IsEmpty();单独的方法不存在.
  • 为什么string.IsNullOrEmpty()存在组合方法?

Jon*_*eet 16

  • string.IsNull 不存在因为你只是检查引用为null
  • string.IsEmpty 因为你可以很容易地用""或长度为0来比较相等性
  • string.IsNullOrEmpty 存在是因为编写单个方法调用比使用更简单

       if (text == null || text.Length == 0)
    
    Run Code Online (Sandbox Code Playgroud)

    (或者反过来).

每个单独的检查都可以单独完成,但将两者结合起来很方便.

  • 不要忘记.NET 4添加了IsNullOrWhitespace.而且这个检查不仅仅是单行代码. (3认同)