由于原來一直都沒注意到這兩個方法,一直使用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相比,肯定是前面一個性能更高,所以還是要選擇性使用的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/216009.html
標籤:.NET技术
上一篇:C#高級編程之泛型一(泛型的引入、泛型的使用、何為泛型)
下一篇:WPF 拉格朗日插值法簡單實作
