我有:
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
label为asp.net label。问题是有时myObject myNestedObject MyNestedObject2或Description是空的我必须在if语句中检查它看起来像:
if(myObject!=null&&myNestedObject!=null&&MyNestedObject2!=null&&Description!=null)
{
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
}
在这个语句中,我检查了四次properties是否为null。是否存在其他方法来检查整个层次结构?
c#空条件操作符的拯救!
摘自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