C# 判斷字符串為空有哪幾種方法


 

Length法:bool isEmpty = (str.Length == 0);
Empty法:bool isEmpty = (str == String.Empty);
General法:bool isEmpty = (str == "");

 

2、深入內部機制: 要深入探討其內部機制,需要查看.Net的源代碼,同樣有三種方法供參考: Rotor法:一個不錯的選擇就是微軟的Rotor,這是微軟的一個源代碼共享項目。 Mono法:另一個不錯的選擇當然就是真正的開源項目Mono啦! Reflector法:最后一個選擇就是使用反編譯器,不過這種重組的代碼不一定就是原貌,只不過是一種“近似值”,可以考慮使用Reflector這個反編譯器[1]。

本文中采用的Reflector法,先來看看一下源代碼[2](片段):

 

public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>
...{
static String()
...{
string.Empty = "";
// Code here
}
// Code here
public static readonly string Empty;
public static bool operator ==(string a, string b)
...{
return string.Equals(a, b);
}
public static bool Equals(string a, string b)
...{
if (a == b)
...{
return true;
}
if ((a != null) && (b != null))
...{
return string.EqualsHelper(a, b);
}
return false;
}
private static unsafe bool EqualsHelper(string ao, string bo)
...{
// Code here
int num1 = ao.Length;
if (num1 != bo.Length)
...{
return false;
}
// Code here
}
private extern int InternalLength();
public int Length
...{
get
...{
return this.InternalLength();
}
}
// Code here
}

 

Rotor里面String類的代碼與此沒什么不同,只是沒有EqualsHelper方法,代之以如下的聲明:

public extern bool Equals(String value);

 

進一步分析: 首先是Empty法,由於String.Empty是一個靜態只讀域,只會被創建一次(在靜態構造函數中)。但當我們使用Empty法進行判空時,.NET還會依次展開調用以下的方法,而后兩個方法內部還會進行對象引用判等!

public static bool operator ==(string a, string b);

public static bool Equals(string a, string b);

private static unsafe bool EqualsHelper(string ao, string bo);

 

若使用General法判等的話,情況就“更勝一籌”了!因為.NET除了要依次展開調用上面三個方法之外,還得首先創建一個臨時的空字符串實例,不適合進行大量的比較。

而對於Length法,則可以繞過上面這些繁瑣的步驟,直接進行整數(字符串長度)判等。 大多數情況下,整數判等都要來得快(我實在想不出比它更快的了,在32位系統上,System.Int32運算最快了)! 另外,在EqualsHelper方法里面.NET會先使用Length法來進行判等! 可惜無法獲得InternalLength方法的代碼。 在Mono的源代碼里面看到了更簡明的實現:

class String
...{
private int length;
public int Length
...{
get
...{
return length;
}
}
// .
}

 

然而使用Length法進行字符串判空串時,要注意,必須先判斷該字符串實例是否為空引用,否則將會拋出NullReferenceException異常! 以下是改進后的Length法:

void Foo(string bar)
...{
if ((bar != null) && (bar.Length == 0))
//
}

 

復制代碼

3、總結: 使用Length法來進行字符串判空串是有着很大的性能優勢的,尤其在進行大量字符串判空時! 當然首先得判斷字符串實例是否為空引用!

好了,今天的內容就介紹到這里了,C#中判斷字符串是否為空的方法,肯定不止這些了,歡迎大家多多交流,有好的辦法分享一下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM