C#优雅的方式来检查,如果一个属性的属性为null [英] C# elegant way to check if a property's property is null
问题描述
在C#中,说,你想拉一个值off PropertyC在这个例子和对象A,PropertyA和PropertyB都可以为空。
In C#, say that you want to pull a value off of PropertyC in this example and ObjectA, PropertyA and PropertyB can all be null.
ObjectA.PropertyA.PropertyB.PropertyC
ObjectA.PropertyA.PropertyB.PropertyC
我如何能得到PropertyC安全与code量最少的?
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;
}
这将是很好做一些更多的这样的(伪code)。
It would be nice to do something more like this (pseudo-code).
int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;
甚至可能进一步坍塌了空合并运算符。
Possibly even further collapsed with a null-coalescing operator.
修改本来我说我的第二个例子就像JS,但我改成了psuedo- code,因为它是正确地指出,它不会在JS工作。
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.
谢谢了,
乔恩
Thanks much, Jon
推荐答案
在C#6你可以用空条件操作。所以原来的考验将是:
In C# 6 you can use the Null Conditional Operator. So the original test will be:
int? value = objectA?.PropertyA?.PropertyB?.PropertyC;
这篇关于C#优雅的方式来检查,如果一个属性的属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!