简体   繁体   English

为什么我需要将null合并运算符放在括号中?

[英]Why do i need to put the null-coalescing operator in brackets?

I have recently noticed a curiosity (at least for me). 我最近注意到了一种好奇心(至少对我而言)。 I thought that the null-coalescing operator would take the precedence over any mathematical operation but obviously i was wrong. 我认为null-coalescing operator会优先于任何数学运算,但显然我错了。 I thought following two variables would have the same value at the end: 我认为以下两个变量在最后会有相同的值:

double? previousValue = null;
double? v1 = 1 + previousValue ?? 0;
double? v2 = 1 + (previousValue ?? 0);

But v2.Value is (the desired) 1 whereas v1.Value is still 0. Why? 但是v2.Value是(期望的)1而v1.Value仍然是0.为什么?

Demo 演示

v1 is 0 for the exact reason you mentioned: the null-coalescing operator actually has relatively low precedence. 由于您提到的确切原因, v1为0:null-coalescing运算符实际上具有相对较低的优先级。 This table shows exactly how low. 该表显示了究竟有多低。

So for the first expression, 1 + null is evaluated first, and it evaluates to a null int? 那么对于第一个表达式,首先计算1 + null ,并计算为null int? , which then coalesces to 0. ,然后合并为0。

v2说,1加(如果previousValue == null将值0添加到1,则给出1.V1表示1加上null为空,所以让我们给出0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM