C#6 Elvis操作符(空传播)是否短路

时间:2015-06-10 19:05:36

标签: c#-6.0

为什么这个c#代码会抛出一个空的异常?

bool boolResult = SomeClass?.NullableProperty.ItsOkProperty ?? false;

一旦NullableProperty评估为null,elvis运营商是否应该停止评估(短路)?

根据我的理解,上面的代码行是:

的快捷方式
bool boolResult 
if(SomeClass != null)
    if(SomeClass.NullableProperty != null)
        boolResult = SomeClass.NullableProperty.ItsOkProperty;
    else
        boolResult = false;
else
    boolResult = false;

我是否认为错了?

编辑:现在我理解为什么我弄错了,代码行实际上转化为类似的东西:

bool boolResult 
if(SomeClass != null)
    boolResult = SomeClass.NullableProperty.ItsOkProperty;
else
    boolResult = false;

因为NullableProperty为空而抛出......

1 个答案:

答案 0 :(得分:9)

你需要链接,因为NRE在第二个引用上:

bool boolResult = SomeClass?.NullableProperty?.ItsOkProperty ?? false;
相关问题