IsNullOrEmpty和IsNullOrWhiteSpace的区别

IsNullOrEmpty和IsNullOrWhiteSpace的区别

「Talk is cheap. Show me the code」

    string strNull = null;
    string strEmpty = string.Empty;
    string space = "";
    string spaces = "   ";  

    Console.WriteLine("---- IsNullOrEmpty  Start ----");
    Console.WriteLine("IsNullOrEmpty(null): {0}", string.IsNullOrEmpty(strNull));
    Console.WriteLine("IsNullOrEmpty(string.Empty): {0}", string.IsNullOrEmpty(strEmpty));
    Console.WriteLine("IsNullOrEmpty(""): {0}", string.IsNullOrEmpty(""));
    Console.WriteLine("IsNullOrEmpty("   "): {0}", string.IsNullOrEmpty("   "));
    Console.WriteLine("---- IsNullOrEmpty  End ----");

    Console.WriteLine();
    Console.WriteLine();

    Console.WriteLine("---- IsNullOrWhiteSpace  Start ----");
    Console.WriteLine("IsNullOrWhiteSpace(null): {0}", string.IsNullOrWhiteSpace(strNull));
    Console.WriteLine("IsNullOrWhiteSpace(string.Empty): {0}", string.IsNullOrWhiteSpace(strEmpty));
    Console.WriteLine("IsNullOrWhiteSpace(""): {0}", string.IsNullOrWhiteSpace(""));
    Console.WriteLine("IsNullOrWhiteSpace("   "): {0}", string.IsNullOrWhiteSpace("   "));
    Console.WriteLine("---- IsNullOrEmpty  End ----");
    Console.ReadKey();

输出结果:

---- IsNullOrEmpty  Start ----
IsNullOrEmpty(null): True
IsNullOrEmpty(string.Empty): True
IsNullOrEmpty(""): True
IsNullOrEmpty("   "): False
---- IsNullOrEmpty  End ----


---- IsNullOrWhiteSpace  Start ----
IsNullOrWhiteSpace(null): True
IsNullOrWhiteSpace(string.Empty): True
IsNullOrWhiteSpace(""): True
IsNullOrWhiteSpace("   "): True
---- IsNullOrEmpty  End ----

IsNullOrEmpty IsNullOrWhiteSpace
null true true
string.Empty true true
"" true true
" " false true

String.IsNullOrEmpty

String.IsNullOrEmpty 方法 (String)

指示指定的字符串是 null 还是 Empty 字符串。

IsNullOrEmpty是一种便利方法,可用于同时测试String是否是null或其值为Empty。 它等效于以下代码︰

	result = s == null || s == String.Empty;

String.IsNullOrWhiteSpace

String.IsNullOrWhiteSpace 方法 (String)

指示指定的字符串是 null、空还是仅由空白字符组成。

IsNullOrWhiteSpace是具有类似于下面的代码,只不过它提供优越性能的便捷方法︰

	return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
原文地址:https://www.cnblogs.com/liushen/p/6756849.html