简体   繁体   English

C#中具有可空类型的+ =运算符

[英]The += operator with nullable types in C#

In C#, if I write 在C#中,如果我写的话

int? x = null;
x += x ?? 1

I would expect this to be equivalent to: 我希望这相当于:

int? x = null;
x = x + x ?? 1

And thus in the first example, x would contain 1 as in the second example. 因此在第一个例子中, x将包含1如第二个例子中所示。 But it doesn't, it contains null. 但它没有,它包含null。 The += operator doesn't seem to work on nullable types when they haven't been assigned. + =运算符在尚未分配时似乎不适用于可空类型。 Why should this be the case? 为什么会这样呢?

Edit : As pointed out, it's because null + 1 = null and operator precedence. 编辑 :正如所指出的,这是因为null + 1 = null和运算符优先级。 In my defence, I think this line in the MSDN is ambiguous!: 在我的辩护中,我认为MSDN中的这一行含糊不清!:

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. 预定义的一元和二元运算符以及值类型存在的任何用户定义的运算符也可以由可空类型使用。 These operators produce a null value if [either of] the operands are null; 如果[操作数]中任何一个为空,则这些运算符产生空值; otherwise, the operator uses the contained value to calculate the result. 否则,运算符使用包含的值来计算结果。

Here is the difference between the two statements: 以下是两个陈述之间的区别:

x += x ?? 1
x = (x + x) ?? 1

The second isn't what you were expecting. 第二个不是你所期待的。

Here's a breakdown of them both: 以下是它们的细分:

x += x ?? 1
x += null ?? 1
x += 1
x = x + 1
x = null + 1
x = null

x = x + x ?? 1
x = null + null ?? 1
x = null ?? 1
x = 1

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

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