Tag: 空的条件运算符

C#优雅的方式来检查属性的属性是否为空

在C#中,假设你想在这个例子中从PropertyC中取出一个值,并且ObjectA,PropertyA和PropertyB都可以为null。 ObjectA.PropertyA.PropertyB.PropertyC 如何以最less的代码安全地获取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中工作。