string.IsNullOrEmpty(string)与string.IsNullOrWhiteSpace(string)

eom*_*off 196 .net c# string

在.NET 4.0及更高版本中,string.IsNullOrEmpty(string)当检查被视为不良操作的字符串时是否使用string.IsNullOrWhiteSpace(string)

Cha*_*thJ 314

最佳做法是选择最合适的一种.

.Net Framework 4.0 Beta 2为字符串提供了一个新的IsNullOrWhiteSpace()方法,它将IsNullOrEmpty()方法概括为除了空字符串之外还包括其他空格.

术语"空白区域"包括屏幕上不可见的所有字符.例如,空格,换行符,制表符和空字符串是空格字符*.

参考:这里

对于性能,IsNullOrWhiteSpace并不理想但是很好.方法调用将导致较小的性能损失.此外,IsWhiteSpace方法本身具有一些可以在不使用Unicode数据时删除的间接.与往常一样,过早优化可能是邪恶的,但它也很有趣.

参考:这里

检查源代码(参考源.NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}
Run Code Online (Sandbox Code Playgroud)

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

例子

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我从来不知道```IsNullOrWhitespace()```是否匹配空字符串.实质上```IsNullOrEmpty()```匹配```IsNullOrWhitespace()```的子集. (8认同)
  • @rob有问题的代码是`return String.IsNullOrEmpty(value) || value.Trim().Length == 0;`,这涉及新的字符串分配和两个单独的检查。最有可能在 IsNullOrWhitespace 中,它是通过单遍完成的,无需任何分配,通过检查字符串中的每个字符是否为空白,因此性能优越。实际上是什么让你感到困惑? (2认同)

Moh*_*yan 153

实践中的差异:

string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();

Result :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = " MDS   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : False

**************************************************************
string testString = "   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : True

**************************************************************
string testString = string.Empty;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = null;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这应该是公认的答案.通过显示实际示例而不是重定向,比接受的答案更有意义. (3认同)

Iva*_*lov 37

它们是不同的功能.你应该根据自己的情况决定你需要什么.

我不认为使用它们中的任何一种都是不好的做法.大部分时间IsNullOrEmpty()都足够了.但你有选择:)

  • @Rfvgyhn:如果你想检查用户名没有空格_anywhere_ - 你应该使用`Contains`.如果你想确保用户名不能包含空格_only_ - `IsNullOrWhiteSpace`就可以了.`IsNullOrEmpty`确保只是以某种方式输入了用户名. (14认同)
  • 例如,注册页面上的用户名字段将使用IsNullOrEmtpy进行验证,因此用户无法使用空格作为其名称. (2认同)

dek*_*dev 28

这是两种方法的实际实现(使用dotPeek反编译)

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

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }
Run Code Online (Sandbox Code Playgroud)

  • 所以这意味着`IsNullOrWhiteSpace`对于`string.Empty`也是如此!这是一个奖金:) (4认同)
  • 是的,最安全的将是使用IsNullOrWhiteSpace(True表示String.empty,null和空格) (4认同)

小智 6

它说这一切IsNullOrEmpty()都不包括白色间距IsNullOrWhiteSpace()!

IsNullOrEmpty()如果字符串是:
-null
-empty

IsNullOrWhiteSpace()如果字符串是:
-null
-empty
-包含白色空间只有

  • 我贬低了,因为当你解释每个功能的作用时,你没有回答实际的问题. (2认同)
  • 您应该编辑您的答案以包含框架定义的“空白”的整个列表:术语“空白”包括屏幕上不可见的所有字符。例如,空格、换行符、制表符和空字符串都是空白字符。 (2认同)