gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:42:34 25 4
gpt4 key购买 nike

在C#中,如果我写

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

我希望这等同于:

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

因此在第一个示例中,x 将包含 1,就像在第二个示例中一样。但它没有,它包含空值。 += 运算符在未分配时似乎不适用于可空类型。为什么会这样?

编辑:如前所述,这是因为 null + 1 = null 和运算符优先级。在我的辩护中,我认为 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.

最佳答案

下面是两个语句之间的区别:

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

第二个不是您所期望的。

以下是它们的分割:

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

关于c# - C# 中具有可空类型的 += 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12711947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com