是否有 shorthand 用于 nullables 的加法赋值运算符,如果为 null 则设置值?

Is there a shorthand for addition assignment operator for nullables that sets the value if null?

我正在使用可为空的双精度数来存储从各种来源提取的一些值的总和。如果不存在任何元素,总和可以是任何实数值或空值。

目前,我使用空检查并赋值或递增:

double? sum = null;
...    
if(sum == null)
    sum = someTempValue;
else
    sum += someTempValue;

我知道 c# 有几个 shorthand 方法调用等的空检查。我的问题是,如果 null 赋值或执行操作 if not null?

您可以输入三元运算符:

double? sum = null;
sum = sum == null ? someTempValue : sum + someTempValue;

或者

sum = someTempValue + (sum == null ? 0 : sum);

sum = someTempValue + (sum ?? 0);

归功于:Dmitry Bychenko 最后一个选项

不是真正的快捷方式,但相当紧凑:

sum = sum ?? 0 + someTempValue;

sum == null 时将 sum 视为 0。但是,请注意 ?? 运算符可能 危险 :

// parenthesis () are mandatory, otherwise you'll have a wrong formula
// (someTempValue + sum) ?? 0;
sum = someTempValue + (sum ?? 0);

从post看不太清楚,但看起来someTempValue不可为nullable,否则if逻辑不会之所以有效,是因为如果 someTempValuenull+ 运算符将破坏之前的总和。

如果这是真的,那么您可以利用空合并运算符和 null + value == null:

这一事实
sum = (sum + someTempValue) ?? someTempValue;

如果 someTempValue 也可以为空,那么正确的逻辑是:

sum = (sum + someTempValue) ?? someTempValue ?? sum;

IMO,不管有没有shorthand,最好把那个逻辑放在一个方法中

public static class MathUtils
{
    public static double? Add(double? left, double? right)
    {
        // The avove shorthand
        return (left + right) ?? right ?? left;
        // or another one
        //return left == null ? right : right == null ? left : left + right;
    }
}

并使用简单

sum = MathUtils.Add(sum, someTempValue);

或使用 C#6 using static 功能,甚至更短

sum = Add(sum, someTempValue);