由於原來一直都沒注意到這兩個方法,一直使用string.IsNullOrEmpty,當看到string.IsNullOrWhiteSpace時,而且在微軟人員開發的項目中經常使用時才注意到,查了一下MSDN,記一下免得以后忘記。
string.IsNullOrEmpty
都知道,這個功能是判斷字符串是否為:null或者string.Empty。如果是如"\t"這樣的字符就返回false了,為了達到判斷過濾這些功能,就要使用Trim()和Length屬性幫忙,判斷是否長度為零,於是乎就產生了如下的方法。
string.IsNullOrWhiteSpace
這個是判斷所有空白字符,功能相當於string.IsNullOrEmpty和str.Trim().Length總和,他將字符串給Char.IsWhiteSpace為ture的任何字符都將是正確的。根據MSDN的說明,這個方法會比調用上述兩個方法的性能更高而且簡潔,所以在判斷這個功能時,推薦使用。
using System; public class Example { public static void Main() { string[] values = { null, String.Empty, "ABCDE", new String(' ', 20), " \t ", new String('\u2000', 10) }; foreach (string value in values) Console.WriteLine(String.IsNullOrWhiteSpace(value)); } } // The example displays the following output: // True // True // False // True // True // True
以上就是代碼執行效果,至於性能就聽微軟的吧,不過string.IsNullOrEmpty和string.IsNullOrWhiteSpace相比,肯定是前面一個性能更高,所以還是要選擇性使用的。
關注公眾號:UP技術控 獲取更多資訊