5

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. 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?

Demo

4

2 回答 2

8

v1由于您提到的确切原因是 0:空合并运算符实际上具有相对较低的优先级。该表准确显示了多低。

因此,对于第一个表达式,1 + null首先计算,然后计算为 a null int?,然后合并为 0。

于 2013-06-28T15:34:05.220 回答
1

v2 说,1 加(如果 previousValue == null 将值 0 加到 1,得到 1。v1 说 1 加 null 为空,所以让我们返回 0。

于 2013-06-28T15:40:19.837 回答