string. isnullorempty (string) vs. string. isnullowhitespace (string)

在。net 4.0及以上版本中有string.IsNullOrWhiteSpace(string)时,检查字符串时使用string.IsNullOrEmpty(string)是否被认为是坏习惯?

138949 次浏览

它们是不同的函数。你应该根据你的情况决定你需要什么。

我不认为使用它们中的任何一种是不好的做法。大多数时候IsNullOrEmpty()就足够了。但你可以选择:)

最好的做法是选择最合适的。

< p >。Net Framework 4.0 Beta 2有一个新的IsNullOrWhiteSpace()方法 字符串,它泛化IsNullOrEmpty()方法,也包括其他白色

术语“空白”包括在屏幕上不可见的所有字符 屏幕上。例如,空格、换行符、制表符和空字符串是白色的 空格字符* > < /强。< / p >

参考:在这里

对于性能来说,IsNullOrWhiteSpace不是很理想,但确实是 好。方法调用将导致较小的性能损失。 此外,IsWhiteSpace方法本身有一些可以实现此功能的间接方法 如果不使用Unicode数据,则删除。一如既往,为时过早 优化可能是邪恶的,但也是有趣的

参考:在这里

检查源代码(参考源代码。net Framework 4.6.2)

IsNullorEmpty

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

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

例子

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

这个怎么样?

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

这将修剪所有的空格,如果它们在那里,避免IsWhiteSpace的性能损失,这将使字符串满足“空”条件,如果它不是空的。

我也认为这是更清楚的,它通常是一个很好的实践,修剪字符串,特别是如果你把它们放入数据库或其他东西。

下面是这两个方法的实际实现(使用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;
}

实践中的差异:

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

它说所有IsNullOrEmpty()不包括白色空格,而IsNullOrWhiteSpace()有!

IsNullOrEmpty()如果字符串是:
空< br > 空< / p >

IsNullOrWhiteSpace()如果字符串是:
空< br > 空< br > -只包含空格

用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();

您将看到IsNullOrWhiteSpace要慢得多:/

string. isnullorempty (str) -如果你想检查字符串值是否已提供

string.IsNullOrWhiteSpace(str)——基本上这已经是一种业务逻辑实现(例如,为什么“”是坏的,但像“~~”这样的东西是好的)。

我的建议——不要把业务逻辑和技术检查混在一起。 例如,字符串。IsNullOrEmpty是最好在方法的开头使用,以检查它们的输入参数

在.Net标准2.0中:

string.IsNullOrEmpty():指示指定的字符串是空字符串还是空字符串。

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

string.IsNullOrWhiteSpace():指示指定的字符串是否为空、空或仅由空白字符组成。

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

注意转义字符:

String.IsNullOrEmpty(""); //True
String.IsNullOrEmpty(null); //True
String.IsNullOrEmpty("   "); //False
String.IsNullOrEmpty("\n"); //False
String.IsNullOrEmpty("\t"); //False
String.IsNullOrEmpty("hello"); //False

在这里:

String.IsNullOrWhiteSpace("");//True
String.IsNullOrWhiteSpace(null);//True
String.IsNullOrWhiteSpace("   ");//True
String.IsNullOrWhiteSpace("\n");//True
String.IsNullOrWhiteSpace("\t");//True
String.IsNullOrWhiteSpace("hello");//False

如果对传递给IsNullOrEmpty()的值应用Trim,两个方法的结果将是相同的。

就性能而言,IsNullOrWhiteSpace()会更快。