在你急于思考之前?null合并运算符:
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
这里的问题是当myParent或objProperty为null时,它会在达到strProperty的评估之前抛出异常.
要避免以下额外的空检查:
if (myParent != null)
{
if (objProperty!= null)
{
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
}
}
Run Code Online (Sandbox Code Playgroud)
我通常使用这样的东西:
string result = ((myParent ?? new ParentClass())
.objProperty ?? new ObjPropertyClass())
.strProperty ?? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
因此,如果对象为null,则它只创建一个新对象才能访问该属性.
哪个不是很干净.
我想要一个像'???'的东西 运营商:
string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
...它将从括号内的任何"null"中存活,以返回默认值.
谢谢你的提示.
Pat*_*man 11
C#6附带的空传播算子怎么样?
string result = (myParent?.objProperty?.strProperty)
?? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
它检查myParent,objProperty并strProperty为null,如果其中任何一个为null,将分配默认值.
我通过创建一个检查空的扩展方法来扩展此功能:
string result = (myParent?.objProperty?.strProperty)
.IfNullOrEmpty("default string value if strObjProperty is null");
Run Code Online (Sandbox Code Playgroud)
在哪里IfNullOrEmpty:
public static string IfNullOrEmpty(this string s, string defaultValue)
{
return !string.IsNullOrEmpty(s) ? s : defaultValue);
}
Run Code Online (Sandbox Code Playgroud)