if語句成立
判定為空字符串的幾種寫法,按照性能從高到低的順序是:
s.Length == 0 優於 s == string.Empty 優於 s == ""
您關於String.Empty和Null的問題是這樣的,這兩個都是表示空字符串,其中有一個重點是string str1= String.Empty和 string str2=null 的區別,這樣定義後,str1是一個空字符串,空字符串是一個特殊的字符串,只不過這個字符串的值為空,在內存中是有准確的指向的,string str2=null,這樣定義後,只是定義了一個string 類的引用,str2並沒有指向任何地方,在使用前如果不實例化的話,都將報錯。textBox1.Text的值為零長度字符串 ""。
So, I just converted a bunch of code that used "" as an empty string like this:
if(myString == "") anotherString = "";
to
if(myString.Equals(String.Empty)) anotherString = String.Empty;
and I''m wondering if I did the right thing, using String.Empty. I hate having quoted strings in code and prefer to stay away from them whenever possible. This generally leads to code that is more strongly typed, and easIEr to maintain, so using String.Empty intuitively feels better than ““. But, I''ve actually found a concrete reason to use String.Empty - I did some research and found that in a test, str.Equals(String.Empty) is faster than comparing to ""! Well, okay. Research isn''t the right Word, “Doing one google search and accepting on faith the first post I saw” is slightly more accurate. I even created a little graph of the claims in this post here, that String.Empty is faster. I''m too lazy to do the test myself, so if you want to verify this, knock yourself out. I do love making graphs though.