2011-12-30 145 views
0

我有這樣的方法:爲什麼`args [0] .Trim()== null`總是假?

public string StartCapture(string[] args) 
{ 
    if(args[0].Trim() == null || args[0].Trim() == string.Empty) 
    { 
     //do stuff 
    } 
} 

爲什麼我收到一張紙條,上面args[0].Trim() == null將永遠是假的?

+3

順便介紹。我相信這個方法對你是有用的:[String.IsNullOrWhiteSpace](http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx)(僅限於.Net 4.0)。 – Ray 2011-12-30 13:03:33

回答

7

Trim()不會返回null。您可能遇到的問題是args[0]爲空或args本身爲空,但Trim()的結果永遠不會爲空,因此與null的比較將始終爲false。

Trim Method

如果當前字符串等於空或在當前實例中的所有字符組成的空白字符,則該方法返回空。

你可能想簡單地檢查

if (args == null || args.Length == 0 || string.IsNullOrWhiteSpace(args[0])) 
{ 
    // null or empty array or empty first element 
} 
+0

爲什麼你檢查字符串的長度是否爲0,如果是這樣的話,那麼它是一個空字符串。你爲什麼不是** IsNullOrEmpty **? – 2011-12-30 13:25:23

+0

我在哪裏檢查了字符串的長度?我只比較了* array *和null,我檢查了*數組*的長度爲0個元素,然後我檢查了第一個元素*僅當有一個時*。請記住,在問題中,它是'字符串[] args'。 – 2011-12-30 13:52:55

2

Trim()被定義爲總是返回一個值,因此,它永遠不能null

0

因爲null不是一個對象,而串.empty(即「」)是一個長度爲0個字符的字符串對象。

3

如果args[0]null,那麼你會得到一個NullReferenceException當您嘗試呼叫Trim()方法。 ==比較中沒有可用的執行路徑,其中null值可用。

可能想:

if(args[0] == null || args[0].Trim() == string.Empty) 
{ 

但更可能想:

if(String.IsNullOrWhitespace(args[0])) 
{ 

String.IsNullOrWhitespace在.NET 4

相關問題