2013-03-27 92 views
54

我通常使用這樣的事情由於種種原因在整個應用程序:一個襯裏如果字符串不爲空,否則空

if (String.IsNullOrEmpty(strFoo)) 
{ 
    FooTextBox.Text = "0"; 
} 
else 
{ 
    FooTextBox.Text = strFoo; 
} 

如果我要去使用它了很多,我將創建一個方法返回所需的字符串。例如:

public string NonBlankValueOf(string strTestString) 
{ 
    if (String.IsNullOrEmpty(strTestString)) 
     return "0"; 
    else 
     return strTestString; 
} 

,並用它喜歡:

FooTextBox.Text = NonBlankValueOf(strFoo); 

好像有什麼事,這是C#的一部分會爲我做到這一點我一直在想。東西,可以這樣調用:

FooTextBox.Text = String.IsNullOrEmpty(strFoo,"0") 

第二個參數是返回的值,如果String.IsNullOrEmpty(strFoo) == true

如果不是有沒有人有他們使用任何更好的方法?

+0

'FooTextBox.Text = foo.IsNullOrEmpty? 「0」:foo;' – 2013-03-27 13:49:33

+1

使用IsNullOrWhiteSpace修剪字符串。 – 2013-03-27 13:54:03

+2

我不會改變你的代碼,除非讓'NonBlankValueOf'靜態。不要依賴C#可能提供的東西 - NonBlankValueOf方法對應用程序具有特定的含義,並且您可以控制該含義。例如,如果您有一天需要將「0」更改爲「1」,該怎麼辦? – 2013-03-27 13:54:52

回答

110

有一個空合併運算符(??),但它不處理空字符串。

如果你只是在處理空字符串感興趣,你可以使用它像

string output = somePossiblyNullString ?? "0"; 

您的需求,具體而言,簡直是有條件的經營者bool expr ? true_value : false_value,您可以使用簡單的if/else語句塊設置或返回一個值。

string output = string.IsNullOrEmpty(someString) ? "0" : someString; 
+2

對於何時使用null coalesc的一個很好的例子來說,+1,儘管OP可能需要它來在他/她的情況下捕獲空字符串。 – 2013-03-27 13:50:26

+0

+1我不知道'''' – 2013-03-27 13:52:16

+0

這一點知道這兩個將使用if-else語句爲我節省無數的浪費時間!這麼簡單,我認爲他們更容易閱讀!謝謝! – user2140261 2013-03-27 14:01:00

7

這可能會幫助:

public string NonBlankValueOf(string strTestString) 
{ 
    return String.IsNullOrEmpty(strTestString)? "0": strTestString; 
} 
12

您可以使用ternary operator

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString 

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo; 
7

你可以寫爲String類型自己Extension方法: -

public static string NonBlankValueOf(this string source) 
{ 
    return (string.IsNullOrEmpty(source)) ? "0" : source; 
} 

現在你可以用任何字符串類型

FooTextBox.Text = strFoo.NonBlankValueOf(); 
+0

我雖然它會是:'FooTextBox.Text = strFoo.NonBlankValueOf();' – Sinatr 2013-03-27 14:14:31

+1

@Sinatr感謝您指出它。它出於匆忙。 – ssilas777 2013-03-27 14:20:37

+0

感謝您的功能:) – SearchForKnowledge 2014-10-20 15:30:02

1

老問題,就像使用它,但認爲我會添加此助陣,

#if DOTNET35 
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0; 
#else 
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ; 
#endif 
相關問題