简体   繁体   English

空结合运算符

[英]Null-coalescing operator

I have the following code: 我有以下代码:

decimal? a = 2m;
decimal? b = 2m;
decimal c = a ?? 1m * b ?? 1m;

Since both a and b have been filled in, I'm expecting c to give me the result of 4 . 由于ab都已填写,我期待c给我4的结果。

However, the result I get is 2 , in which case b is taken as 1 instead of 2 . 但是,我得到的结果是2 ,在这种情况下, b被视为1而不是2

Does anyone know what is the reason behind this behaviour? 有谁知道这种行为背后的原因是什么?

group the value condition if you want to get the value of 4 如果要获取值4则将值条件分组

decimal c = (a ?? 1m) * (b ?? 1m);

your current syntax is evaluated as 您当前的语法被评估为

decimal c = a ?? (1m * b ?? 1m);

and the reason why you get the value of 2 ( as for a ) 以及你得到2的值的原因( 至于a

The expression works as: 表达式如下:

decimal c = a ?? (1m * b) ?? 1m;

As a has a value, you get that. 作为a有价值,你得到了。

decimal c = a ?? 1m * b ?? 1m;

Equals to: 等于:

if (a != null)
    c = a
else
    ...

In your case a is not null and has the value of 2 so this is the result. 在您的情况下, a不为null并且值为2因此这是结果。

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

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