程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> String.Empty,NULL和的區別

String.Empty,NULL和的區別

編輯:.NET實例教程
string.Empty不分配存儲空間
      ""分配一個長度為空的存儲空間   
      所以一般用string.Empty

為了以後跨平台,還是用string.empty

在 C# 中,大多數情況下 "" 和 string.Empty 可以互換使用。比如:
string s = "";
string s2 = string.Empty;

if (s == string.Empty) {
  //
}

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的值為零長度字符串 ""。

String.Empty vs. ""


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.


也就是說 判斷字符串是否為空best的方法就是     str.Length==0 !
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved