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

时间:2011-06-26 08:56:30

标签: c# .net string

如果string.Empty != null创建string.IsNullOrEmpty()为什么?

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

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

2 个答案:

答案 0 :(得分:16)

  • string.IsNull不存在,因为您只是检查引用为空
  • string.IsEmpty不存在,因为您可以轻松地将相等性与“”或长度为0进行比较
  • string.IsNullOrEmpty存在是因为编写单个方法调用比使用

    更简单
       if (text == null || text.Length == 0)
    

    (当然,反过来)。

每个单独的检查都可以单独进行,但将两者结合起来很方便。

答案 1 :(得分:1)

用于检查输入字符串是否有效。 (例如,不为空而不是空)。 因此,您不希望每次都要确保这两项检查,这就是它的原因。 如果您想检查其中任何一个,只需使用== null== ""比较。

相关问题