我需要添加许多类型为nullable 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();
}
}
}
简单,简洁,并与东西已经在那里工作。 +1 – stakx 2010-08-30 10:31:16
你的方法比单纯执行'int total =(sum1 ?? 0)+(sum2 ?? 0)+(sum3 ?? 0)更好吗?我的意思是你创建一个数组只是为了总结它们的值。它影响很大吗?我只想知道,尽管我先写了类似的代码,然后再来搜索它;-) – 2017-02-05 05:57:52