在C#中,假设您希望从本例中的PropertyC中提取一个值,而ObjectA、PropertyA和PropertyB都可以为null。
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,但我将其更改为psuedo代码,因为正确地指出它在js中不能工作。
发布于 2013-12-09 13:26:58
只是在这个帖子上绊倒了。
不久前,我就Visual提出了关于添加一个新的???操作符的建议。
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4104392-add-as-an-recursive-null-reference-check-opera
这将需要框架团队的一些工作,但不需要改变语言,而只需要做一些编译器魔术。这个想法是编译器应该修改这个代码(语法不允许atm)。
string product_name = Order.OrderDetails[0].Product.Name ??? "no product defined";转到这个代码中
Func<string> _get_default = () => "no product defined";
string product_name = Order == null
? _get_default.Invoke()
: Order.OrderDetails[0] == null
? _get_default.Invoke()
: Order.OrderDetails[0].Product == null
? _get_default.Invoke()
: Order.OrderDetails[0].Product.Name ?? _get_default.Invoke()对于空检查,这可能如下所示
bool isNull = (Order.OrderDetails[0].Product ??? null) == null;https://stackoverflow.com/questions/3468250
复制相似问题