2011-11-22 179 views

回答

110
if (string.IsNullOrEmpty(myString)) { 
    // 
} 
+1

當我使用'IsEmpty'它說:''字符串'不包含IsEmpty'的定義,我可以在[msdn]中使用'IsEmpty'(https://msdn.microsoft.com/zh-cn/library/system.web.webpages.stringextensions .isempty%28v = vs.99%29.aspx)還是應該使用'IsNullOrEmpty'? – stom

+2

非常簡單而實用。我希望PHP可以有這樣的東西 –

+3

@Lion Liu:其實我認爲PHP提供的東西完全一樣。請參閱:http://php.net/manual/en/function.empty.php – Milan

6

如果變量是一個字符串

bool result = string.IsNullOrEmpty(variableToTest); 

,如果你只有一個對象可能會或可能不會包含一個字符串,然後

bool result = string.IsNullOrEmpty(variableToTest as string); 
+1

我有同樣的問題,第二個不能正常工作。試試這個: object x = 3; bool result = string.IsNullOrEmpty(x as string); 'x as string'將爲空,因此儘管x的值不是null或空字符串,但結果仍然爲真。我沒有找到一個簡短的解決方案,使用雙重檢查。 –

+0

@MártonMolnár它將不得不包含一個字符串3不是一個字符串,所以這是預計嘗試使用「3」而不是 –

1

把戲:

Convert.ToString((object)stringVar) == 「」 

這是可行的,因爲Convert.ToString(object )如果object爲null,則返回一個空字符串。 Convert.ToString(string)如果string爲null,則返回null。

(或者,如果你使用.NET 2.0,你可以使用總是String.IsNullOrEmpty。)

+4

儘管技術上正確,但我可以斷然說我從來沒有見過這種方法使用。 –

+0

爲什麼?........... – Liam

+0

我們是否認爲將stringVar轉換爲一個強制轉換對象會返回空字符串,分配給stringVar變量的空字符串和空字符串,強制轉換返回null和空字符串?我只是想找出所有的變化..... – Stokely

28

由於.NET 2.0,你可以使用:

// Indicates whether the specified string is null or an Empty string. 
string.IsNullOrEmpty(string value); 

此外,由於.NET 4.0有這麼去更遠一些的新方法:

// Indicates whether a specified string is null, empty, or consists only of white-space characters. 
string.IsNullOrWhiteSpace(string value); 
1
if (string.IsNullOrEmpty(myString)) 
{ 
    . . . 
    . . . 
} 
相關問題