空合并运算符和操作顺序?

Null-coalescing operator and order of operations?

任何人都可以向我解释为什么这个代码:

int? a = 54;
decimal b = a ?? 0 / 100m;

b 的值为 54 ?

但是如果我添加一些括号:

int? a = 54;
decimal b = (a ?? 0) / 100m;

它的值为0.54?

我不明白为什么会这样。因为 a 的值为 54,所以我认为 ?? 运算符什么都不做。

int? a = 54;
decimal b = (a ?? 0) / 100m;

如您所见,计算结果为 b = (54) / 100mb = 0.54

From MSDN:

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

在你的第一个案例中,

int? a = 54;  //Here "a" is not null
decimal b = a ?? 0 / 100m; //As "a" is not null, Value of "a" will be assigned to "b".

在你的第二种情况下,

  // precedence of "(<expression>)" is greater than "null coalescing operator" 
  int b = (a ?? 0) / 100m;
          //+++++++        --This will evaulate first and returns 54
         //          +++  -- This will be calculated as 54 / 100m i.e 0.54

?? has lower 优先于 /.

1 个案例:

54 ?? (0 / 100) == 54

2 个案例:

(54 ?? 0) / 100 == 0.54

一点想法:

decimal b = a ?? 0 / 100m;

相当于:

decimal b = a ?? (0 / 100m);

所以 100 不适用于第一种情况

decimal b = a ?? 0 / 100m;  

评估为

decimal b;
if (a == null)
{
    b = 0 / 100m;
}
else
{
    b = a;
}

这纯粹是运算符优先级的问题。

The documentation lists the order of precedence对于不同的运算符,你会看到/的优先级高于??,这意味着它会被优先计算。

所以,

decimal b = a ?? 0 / 100m;

总是计算为

decimal b = a ?? (0 / 100m);