空字符串,如果为null

我的代码中有这个:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString()) 

当它返回null时它会给出一个错误,如果它为null,我怎么能使它成为一个空字符串?

/ M

(C#6.0更新)

如果您使用的是C#6或更新版本(Visual Studio 2015或更新版本),那么您可以使用空条件运算符来实现此目的?.

 var customerId = cu.Customer?.CustomerId.ToString() ?? ""; 

null条件运算符的一个有用属性是,如果要测试多个嵌套属性是否为null,它也可以“链接”:

 // ensure (a != null) && (b != null) && (c != null) before invoking // abcCustomerId, otherwise return "" (short circuited at first encountered null) var customerId = a?.b?.c?.CustomerId.ToString() ?? ""; 

对于6.0之前的C#版本 (VS2013或更早版本),您可以像这样合并它:

 string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : ""; 

在尝试访问其成员之前,只需检查对象是否为非null,否则返回空字符串。

除此之外,还有一些空对象模式很有用的情况。 这意味着您确保Customer的父类(在这种情况下为cu类型) 始终返回对象的实际实例,即使它是“空”。 如果您认为它可能适用于您的问题,请查看此链接以获取示例: 如何在C#中创建Null对象 。

它取决于CustomerID的类型。

如果CustomerID是字符串,那么您可以使用null合并运算符 :

 SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty) 

如果CustomerIDNullable ,那么您可以使用:

 SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString()) 

这将起作用,因为如果实例为null ,则NullableToString()方法返回空字符串(技术上,如果HasValue属性为false )。

三元运算符可以工作,但是如果你想要更短的表达式处理任意对象,你可以使用:

 (myObject ?? "").ToString() 

以下是我的代码中的真实示例:

  private HtmlTableCell CreateTableCell(object cellContents) { return new HtmlTableCell() { InnerText = (cellContents ?? "").ToString() }; } 
 SelectList(blah, "blah", "blah", (cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"") ) 

请不要在生产中使用它:

 ///  /// I most certainly don't recommend using this in production but when one can abuse delegates, one should :) ///  public static class DirtyHelpers { public static TVal SafeGet(this THolder holder, Func extract) where THolder : class { return null == holder ? default(TVal) : extract(); } public static void Sample(String name) { int len = name.SafeGet(()=> name.Length); } }