我有:
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
其中label是asp.net标签。问题是,有时myObject,myNestedObject,MyNestedObject2或Description为null,我必须在if语句中检查它,如下所示:
if(myObject!=null&&myNestedObject!=null&&MyNestedObject2!=null&&Description!=null)
{
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
}
在这个语句中,我检查四次属性是否为null。是否存在检查整个层次结构的任何其他方法?
答案 0 :(得分:1)
C# null-conditional operators救援!
取自MSDN网站:
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null