1 如果在 C# 中为 null,则以线性、美观和干净的方式分配值?

1 linear, beauty and clean way to assign value if null in C#?

赶在你之前想想??空合并运算符:

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" 到 return 默认值而不是。

感谢您的提示。

C# 6 附带的 null 传播运算符怎么样?

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);
}