在 C # 中,假设在这个示例中您想从 PropertyC 中取出一个值,那么 ObjectA、 PropertyA 和 PropertyB 都可以是 null。
PropertyA.PropertyB.PropertyC
How can I get PropertyC safely with the least amount of code?
现在我要检查一下:
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;
甚至可能使用空聚合运算符进一步崩溃。
EDIT Originally I said my second example was like js, but I changed it to psuedo-code since it was correctly pointed out that it would not work in js.