空检查先前条件语句的空传播替换 [英] Null-propagation replacement for null check prior conditional statement
问题描述
在看到一个类似问题后,我想知道以下表达式是否...
After seeing a similar question, I was wondering if the following expression ...
if (attribute != null && attribute.Description == input)
... 的行为(几乎)与以下空传播变体相同?
... would behave (almost) identical, to following null-propagation variant?
if (attribute?.Description == input)
到目前为止,我只能确定以下(某种程度上是微小的)差异:
So far, I could determine only following (somehow minor) differences:
- 不可能在
input
是不可为空类型的情况下 - 如果
input
本身是null
,则行为会改变
- not possible in case
input
is of non-nullable type - in case
input
would be itselfnull
, behavior would be altered
我错过了什么吗?或者还有其他行为差异?
Am I missing something? or are there other differences in behavior?
最后,我为第一个片段找到的唯一故障安全替代方法是:
in the end, the only fail-safe alternative I've found for the first snippet, would be:
if (attribute?.Description?.Equals(input) ?? false)
推荐答案
如果 input
是不可为 null 的类型,代码将工作.所有不可为空类型都隐式转换为可空类型,因此 input
将被简单地提升为可空类型以与属性值进行比较.
The code will work if input
is of a non-nullable type. There is an implicit conversion of all non-nullable types to their nullable counterparts, so input
will simply be lifted to a nullable to be compared to the property value.
行为上的唯一区别,正如你提到的,如果 input
是 null
,那么第二个片段就无法区分 attribute
是 null
,什么时候应该是 false
,而 Description
是 null
,哪里应该是 <代码>真代码>.
The only difference in behavior, as you mentioned is that, if input
is null
, then the second snippet has no way of differentiating between attribute
being null
, when it should be false
, and where Description
is null
, where it should be true
.
哦,这是假设 attribute
是一个局部变量或字段.如果它是一个属性(或者实际上是一个更复杂的表达式),那么它可能会产生副作用或在计算两次时导致不同的值,就像第一个片段中发生的那样,第二个片段中发生的情况不同,这是行为上的差异.
Oh, and this is assuming that attribute
is a local variable or field. If it's a property (or is actually a more complex expression) then it could have side effects or result in a different value when computed twice, as happens in the first snippet but not the second, which is a difference in behavior.
这当然是假设一个单线程上下文.在多线程上下文中,如果 attribute
可从另一个线程访问(因为它是一个可访问的字段,或者因为它在暴露给另一个线程的 lambda 中关闭),则该值每次都可能不同它是计算出来的,所以这两个片段不同的原因与上一段中描述的相同.
This is all of course assuming a single threaded context. In a multithreaded context, if attribute
is accessible from another thread (either because it's a field that's accessible or because it's closed over in a lambda that is exposed to another thread) then the value could be different each time it's computed, so the two snippets differ for the same reason described in the previous paragraph.
这篇关于空检查先前条件语句的空传播替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!