不一致的空值引用异常

Avi*_*mar -1 c# asp.net nullreferenceexception

当我尝试从序列化类对象存储我的值时,我面临不一致的空值引用错误.

if ( item.current_location.city!=null )
{
    var city = item.current_location.city.Select(i => i.ToString());
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,即使item数组中的任何索引具有空值,也会成功插入.但它在某些情况下抛出异常,我认为不能以任何方式区分其他情况(当值为null时)

Oli*_*bes 5

item 也可以为空

current_location 也可以为null,

不仅如此city.

这会有所帮助

if (item != null && 
    item.current_location != null && 
    item.current_location.city != null) {
    ...
} 
Run Code Online (Sandbox Code Playgroud)

编辑:

注意:此代码有效,因为c#实现了对布尔表达式的所谓快捷方式评估.如果item应该null,则不会评估表达式的其余部分.如果 item.current_location应该null,则不会评估最后一个术语.


(我在上面的代码中看不到任何插入.)


从C#6.0开始,您可以使用空传播运算符(?):

var city = item?.current_location?.city?.Select(i => i.ToString());
if (city != null) {
     // use city ...
}
Run Code Online (Sandbox Code Playgroud)