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;