问题
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;
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
?
回答1:
You could put ternary operator:
double? sum = null;
sum = sum == null ? someTempValue : sum + someTempValue;
Or
sum = someTempValue + (sum == null ? 0 : sum);
Or
sum = someTempValue + (sum ?? 0);
Credit to: Dmitry Bychenko for the last option
回答2:
Not a real shortcut, but quite compact:
sum = sum ?? 0 + someTempValue;
treat sum
as 0
when sum == null
. But, please, notice that ??
operator can be dangerous:
// parenthesis () are mandatory, otherwise you'll have a wrong formula
// (someTempValue + sum) ?? 0;
sum = someTempValue + (sum ?? 0);
回答3:
It's not quite clear from the post, but looks like the someTempValue
is non nullable, otherwise the if
logic will not work because +
operator will destroy the previous sum if the someTempValue
is null
.
If that's true, then you can utilize the null-coalescing operator and the fact that null + value == null
:
sum = (sum + someTempValue) ?? someTempValue;
If someTempValue
is also nullable, then the correct logic would be:
sum = (sum + someTempValue) ?? someTempValue ?? sum;
IMO, with shorthand or not, it's better to put that logic in a method
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;
}
}
and use simple
sum = MathUtils.Add(sum, someTempValue);
or with C#6 using static
feature, the even shorter
sum = Add(sum, someTempValue);
来源:https://stackoverflow.com/questions/37295114/is-there-a-shorthand-for-addition-assignment-operator-for-nullables-that-sets-th