1个线性,美观和干净的方式在C#中为null赋值?

时间:2016-04-29 09:10:31

标签: c# null-check

在你急于思考之前? null合并运算符:

string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";

这里的问题是当myParent或objProperty为null时,它会在达到strProperty的评估之前抛出异常。

要避免以下额外的空检查:

if (myParent != null)
{
   if (objProperty!= null)
   {
       string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
   }
}

我通常使用这样的东西:

string result = ((myParent ?? new ParentClass())
                .objProperty ?? new ObjPropertyClass())
                .strProperty ?? "default string value if strObjProperty is null";

因此,如果对象为null,则它只创建一个新对象才能访问该属性。

哪个不是很干净。

我想要像“' ???'操作者:

string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";

......无论如何都能生存下去" null"从括号内部返回默认值。

感谢您的提示。

1 个答案:

答案 0 :(得分:11)

C#6附带的空传播算子怎么样?

string result = (myParent?.objProperty?.strProperty)
                ?? "default string value if strObjProperty is null";

它会检查myParentobjPropertystrProperty是否为空,如果其中任何一个为空,则会分配默认值。

我通过创建一个检查空的扩展方法扩展了这个功能:

string result = (myParent?.objProperty?.strProperty)
                .IfNullOrEmpty("default string value if strObjProperty is null");

IfNullOrEmpty只是:

public static string IfNullOrEmpty(this string s, string defaultValue)
{
    return !string.IsNullOrEmpty(s) ?  s : defaultValue);
}