【发布时间】:2011-03-28 22:48:03
【问题描述】:
在 C# 中,假设您想在此示例中从 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 中不起作用。
【问题讨论】:
标签: c# nullreferenceexception nullable null-conditional-operator