简体   繁体   English

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

[英]string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

在使用的string.IsNullOrEmpty(string)检查认为是不好的做法,一个字符串时,当有string.IsNullOrWhiteSpace(string)在.NET 4.0及以上?

The best practice is selecting the most appropriate one. 最佳做法是选择最合适的一种。

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string. .Net Framework 4.0 Beta 2为字符串提供了一个新的IsNullOrWhiteSpace()方法,它将IsNullOrEmpty()方法概括为除了空字符串之外还包括其他空格。

The term “white space” includes all characters that are not visible on screen. 术语“空白区域”包括屏幕上不可见的所有字符。 For example, space, line break, tab and empty string are white space characters* . 例如,空格,换行符,制表符和空字符串是空格字符*

Reference : Here 参考: 这里

For performance, IsNullOrWhiteSpace is not ideal but is good. 对于性能,IsNullOrWhiteSpace并不理想但是很好。 The method calls will result in a small performance penalty. 方法调用将导致较小的性能损失。 Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. 此外,IsWhiteSpace方法本身具有一些可以在不使用Unicode数据时删除的间接。 As always, premature optimization may be evil, but it is also fun. 与往常一样,过早优化可能是邪恶的,但它也很有趣。

Reference : Here 参考: 这里

Check the source code (Reference Source .NET Framework 4.6.2) 检查源代码 (参考源.NET Framework 4.6.2)

IsNullorEmpty IsNullorEmpty

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

IsNullOrWhiteSpace 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;
}

Examples 例子

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

The differences in practice : 实践中的差异:

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

They are different functions. 它们是不同的功能。 You should decide for your situation what do you need. 你应该根据自己的情况决定你需要什么。

I don't consider using any of them as a bad practice. 我不认为使用它们中的任何一种都是不好的做法。 Most of the time IsNullOrEmpty() is enough. 大多数时候IsNullOrEmpty()就足够了。 But you have the choice :) 但你有选择:)

Here is the actual implementation of both methods ( decompiled using dotPeek) 这是两种方法的实际实现(使用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;
    }

It says it all IsNullOrEmpty() does not include white spacing while IsNullOrWhiteSpace() does! 它说所有IsNullOrEmpty()都不包括白色间距,而IsNullOrWhiteSpace()呢!

IsNullOrEmpty() If string is: IsNullOrEmpty()如果string是:
-Null -空值
-Empty -empty

IsNullOrWhiteSpace() If string is: IsNullOrWhiteSpace()如果string是:
-Null -空值
-Empty -empty
-Contains White Spaces Only - 仅包含空白区域

What about this for a catch all... 怎么样才能抓住所有......

if (string.IsNullOrEmpty(x.Trim())
{
}

This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null. 这将修剪所有空格,如果它们在那里避免IsWhiteSpace的性能损失,这将使字符串满足“空”条件,如果它不为空。

I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something. 我也认为这是更清晰的,无论如何都要修剪字符串,特别是如果你将它们放入数据库或其他东西。

Check this out with IsNullOrEmpty and IsNullOrwhiteSpace 使用IsNullOrEmpty和IsNullOrwhiteSpace进行检查

string sTestes = "I like sweat peaches";
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < 5000000; i++)
    {
        for (int z = 0; z < 500; z++)
        {
            var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
        }
    }

    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
    Console.ReadLine();

You'll see that IsNullOrWhiteSpace is much slower :/ 你会看到IsNullOrWhiteSpace要慢得多:/

string.IsNullOrEmpty(str) - if you'd like to check string value has been provided string.IsNullOrEmpty(str) - 如果你想检查字符串值已被提供

string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (ie why " " is bad, but something like "~~" is good). string.IsNullOrWhiteSpace(str) - 基本上这已经是一种业务逻辑实现(即为什么“”很糟糕,但像“~~”这样的东西很好)。

My advice - do not mix business logic with technical checks. 我的建议 - 不要将业务逻辑与技术检查混合在一起。 So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters. 因此,例如,string.IsNullOrEmpty最好在方法开头使用,以检查其输入参数。

In the .Net standard 2.0: 在.Net标准2.0中:

string.IsNullOrEmpty() : Indicates whether the specified string is null or an Empty string. string.IsNullOrEmpty() :指示指定的字符串是null还是空字符串。

Console.WriteLine(string.IsNullOrEmpty(null));           // True
Console.WriteLine(string.IsNullOrEmpty(""));             // True
Console.WriteLine(string.IsNullOrEmpty(" "));            // False
Console.WriteLine(string.IsNullOrEmpty("  "));           // False

string.IsNullOrWhiteSpace() : Indicates whether a specified string is null, empty, or consists only of white-space characters. string.IsNullOrWhiteSpace() :指示指定的字符串是空,空还是仅包含空格字符。

Console.WriteLine(string.IsNullOrWhiteSpace(null));     // True
Console.WriteLine(string.IsNullOrWhiteSpace(""));       // True
Console.WriteLine(string.IsNullOrWhiteSpace(" "));      // True
Console.WriteLine(string.IsNullOrWhiteSpace("  "));     // True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 string.IsNullOrWhiteSpace()和string.IsNullOrEmpty()中的NullReferenceException - NullReferenceException in string.IsNullOrWhiteSpace() and string.IsNullOrEmpty() string.IsNullOrEmpty &amp; string.IsNullOrWhiteSpace 为空字符串返回 false - string.IsNullOrEmpty & string.IsNullOrWhiteSpace return false for empty string Java等价于c#String.IsNullOrEmpty()和String.IsNullOrWhiteSpace() - Java equivalent of c# String.IsNullOrEmpty() and String.IsNullOrWhiteSpace() string.IsNullOrEmpty(myString.Trim()) 与 string.IsNullOrWhiteSpace(myString) - string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString) string.IsNullOrEmpty(myString)或string.IsNullOrWhiteSpace(myString)是否违反了SRP规则? - string.IsNullOrEmpty(myString) or string.IsNullOrWhiteSpace(myString) is not violating SRP Rule? .NET string.IsNullOrWhiteSpace实现 - .NET string.IsNullOrWhiteSpace implementation LINQ 表达式中的 String.IsNullOrWhiteSpace - String.IsNullOrWhiteSpace in LINQ Expression string.IsNullOrEmpty() 与 string.NotNullOrEmpty() - string.IsNullOrEmpty() vs string.NotNullOrEmpty() String.IsNullOrEmpty()或IsEmpty() - String.IsNullOrEmpty() or IsEmpty() String.IsNullOrEmpty 单子 - String.IsNullOrEmpty Monad
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM