是否有可空值的加法赋值运算符的简写,如果为空则设置值? [英] Is there a shorthand for addition assignment operator for nullables that sets the value if null?
问题描述
我使用可空双精度来存储从各种来源提取的某些值的总和.如果不存在任何元素,则总和可以是任何实数值或 null.
I am using nullable doubles to store the sum of some values pulled from various sources. The sum could be any real value or null if no elements are present.
目前,我使用空检查并分配或递增:
Currently, I use a null check and either assign or increment:
double? sum = null;
...
if(sum == null)
sum = someTempValue;
else
sum += someTempValue;
我知道 c# 有几个对方法调用等的速记空检查.我的问题是,当使用可空值时,如果 null
分配值或 not null代码>?
I know c# has several shorthand null checks for method calls and the such. My question is if there is a shorthand notation to the addition assignment operator +=
when using nullables that assigns the value if null
or performs the operation if not null
?
推荐答案
你可以放三元运算符:
double? sum = null;
sum = sum == null ? someTempValue : sum + someTempValue;
或
sum = someTempValue + (sum == null ? 0 : sum);
或者
sum = someTempValue + (sum ?? 0);
归功于:Dmitry Bychenko 最后一个选项
Credit to: Dmitry Bychenko for the last option
这篇关于是否有可空值的加法赋值运算符的简写,如果为空则设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!