空字符串,如果为null

时间:2009-11-02 09:41:19

标签: c# asp.net-mvc

我的代码中有这个:

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

当它返回null时出现错误,如何使其成为空字符串如果为空,则CustomerID为空字符串?

/ M

5 个答案:

答案 0 :(得分:51)

(C#6.0更新)

如果您使用的是C#6或更新版本(Visual Studio 2015或更新版本),则可以使用null-conditional operator ?.实现此目的:

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

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

// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, 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,否则返回空字符串。

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

答案 1 :(得分:18)

(C#2.0 - C#5.0)

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

(myObject ?? "").ToString()

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

 private HtmlTableCell CreateTableCell(object cellContents)
 {
     return new HtmlTableCell()
     {
         InnerText = (cellContents ?? "").ToString()             
     };
 }

答案 2 :(得分:16)

取决于CustomerID的类型。

如果CustomerID是字符串,那么您可以使用null coalescing operator

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

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

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

这将有效,因为如果实例为Nullable<T>null false方法返回空字符串(技术上,如果ToString()属性为{{1}})

答案 3 :(得分:1)

SelectList(blah, "blah", "blah", 
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)

答案 4 :(得分:0)

请不要在生产中使用它:

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

    public static void Sample(String name)
    {
        int len = name.SafeGet(()=> name.Length);
    }
}