【发布时间】:2011-04-05 16:36:54
【问题描述】:
我需要添加大量可为 null 的 int 类型的变量。我使用空合并运算符将其降低为每行一个变量,但我觉得有一种更简洁的方法可以做到这一点,例如我不能以某种方式将这些语句链接在一起吗,我以前在其他代码中看到过。
using System;
namespace TestNullInts
{
class Program
{
static void Main(string[] args)
{
int? sum1 = 1;
int? sum2 = null;
int? sum3 = 3;
//int total = sum1 + sum2 + sum3;
//int total = sum1.Value + sum2.Value + sum3.Value;
int total = 0;
total = total + sum1 ?? total;
total = total + sum2 ?? total;
total = total + sum3 ?? total;
Console.WriteLine(total);
Console.ReadLine();
}
}
}
【问题讨论】:
-
提供的解决方案的问题是空值之和为零。在某些情况下,您希望所有空值的总和为空。例如诠释?添加=空,更新=空,删除=空;诠释?总计 = 添加 + 更新 + 删除; // null 即什么都没做。
标签: c# nullable null-coalescing-operator