PropertyC
中获取一个值,而ObjectA
、PropertyA
和PropertyB
都可以为空。ObjectA.PropertyA.PropertyB.PropertyC
如何以最少的代码安全地获取PropertyC
?
目前我会检查:
if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
// safely pull off the value
int value = objectA.PropertyA.PropertyB.PropertyC;
}
做类似于这样的事情会很不错(伪代码)。
int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;
甚至可以使用空值合并运算符进一步简化。
编辑:最初我说我的第二个示例类似于js,但我将其更改为伪代码,因为正确指出它在js中不起作用。
PropertyC
为空,value
等于什么?如果PropertyB
为空呢?如果Object A
为空呢? - Kellen Stuartif(propertyX == null) {value = null} else if (propertyY == null){ value = null} else if......
,最终的表达式是if(propertyZ != null) { value = propertyZ }
。 - DetectivePikachuobjectA == null || objectA.PropertyA == null || objectA.PropertyA.PropertyB == null ? null : objectA.PropertyA.PropertyB.PropertyC
。 - ToolmakerSteve