2010-05-25 47 views
4

什麼是編寫健壯代碼的最佳方式,以便可以檢查變量是否爲空和空白。空值和空值

例如

string a; 

if((a != null) && (a.Length() > 0)) 
{ 
    //do some thing with a 
} 
+0

你從哪裏聽說過C#.Net?哪有這回事。 – 2010-05-25 09:01:52

回答

7

對於字符串,有

if (String.IsNullOrEmpty(a)) 
+2

更好的使用String.IsNullOrEmpty() – 2010-05-25 09:30:36

+0

'string'擊敗'String',因爲你不必按shift鍵,讓你的鍵盤保持更長的時間,並且讓你不那麼累,再加上你不需要'使用System;爲小寫版本。 (開玩笑,申請和+1正確的大寫當清楚地訪問一個靜態類方法) – 2011-12-06 09:19:28

1

從2.0版本,你可以使用IsNullOrEmpty

string a; 
... 
if (string.IsNullOrEmpty(a)) ... 
0

字符串:

string a; 
if(!String.IsNullOrEmpty(a)) 
{ 
//do something with a 
} 

特定類型,你可以創建一種推廣方法 請注意,我用的HasValue代替IsNullorEmpty因爲時間的99%,你將不得不使用! - 運算符如果使用IsNullOrEmpty我覺得這很不可讀

public static bool HasValue(this MyType value) 
{ 
//do some testing to see if your specific type is considered filled 
} 
3

您可以定義一個擴展方法,讓你做這個事情太多了:

static public bool IsNullOrEmpty<T>(this IEnumerable <T>input) 
{ 
    return input == null || input.Count() == 0; 
} 

它已經作爲字符串的System.String類的靜態方法存在,正如已經指出的那樣。

+2

引用約翰Skeet: 但是,你一定要使用Any()。這樣它只需要測試第一個元素的存在。對於正常實現ICollection ,這將非常便宜,但對於涉及複雜查詢的情況,可能會比Count()快得多*。 http://danielvaughan.orpius.com/post/IEnumerable-IsNullOrEmpty.aspx – 2010-05-25 10:01:17

0
if(string.IsNullOrEmpty(string name)) 
{ 
    /// write ur code 
} 
0

我發現Apache的Commons.Lang StringUtils的(JAVA)的命名輕鬆了不少:isEmpty()檢測爲null或空字符串,的isBlank()檢查空,空字符串或空格只。 isNullOrEmpty可能更具描述性,但空和空,在大多數情況下,您使用它,同樣的事情。