Ifstring的一个class轮不是空的或空的
在整个应用程序中,我通常会以各种理由使用这样的东西:
if (String.IsNullOrEmpty(strFoo)) { FooTextBox.Text = "0"; } else { FooTextBox.Text = strFoo; } 如果我打算使用它,我会创build一个返回所需string的方法。 例如:
 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 
如果没有人有更好的方法,他们使用?
 有一个空合并运算符( ?? ),但它不会处理空string。 
如果你只对处理空string感兴趣,你可以使用它
 string output = somePossiblyNullString ?? "0"; 
 为了您的需要,有简单的条件运算符bool expr ? true_value : false_value  bool expr ? true_value : false_value ,您可以简单地使用/ else语句块设置或返回值。 
 string output = string.IsNullOrEmpty(someString) ? "0" : someString; 
你可以使用三元运算符 :
 return string.IsNullOrEmpty(strTestString) ? "0" : strTestString FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo; 
这可能有助于:
 public string NonBlankValueOf(string strTestString) { return String.IsNullOrEmpty(strTestString)? "0": strTestString; } 
您可以编写您自己的扩展方法的stringtypes: –
  public static string NonBlankValueOf(this string source) { return (string.IsNullOrEmpty(source)) ? "0" : source; } 
现在你可以像使用任何stringtypes一样使用它
 FooTextBox.Text = strFoo.NonBlankValueOf(); 
老问题,但认为我会添加这个帮助,
 #if DOTNET35 bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0; #else bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ; #endif