Edw*_*uay 34 c# nullable null-coalescing-operator
我需要添加许多类型为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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ani*_*Ani 52
var nums = new int?[] {1, null, 3};
var total = nums.Sum();
Run Code Online (Sandbox Code Playgroud)
这依赖于IEnumerable<Nullable<Int32>>超载的的Enumerable.Sum方法,其行为如你所愿.
如果您的默认值不等于零,则可以执行以下操作:
var total = nums.Sum(i => i.GetValueOrDefault(myDefaultValue));
Run Code Online (Sandbox Code Playgroud)
或速记:
var total = nums.Sum(i => i ?? myDefaultValue);
use*_*910 12
只是直接回答这个问题:
int total = (sum1 ?? 0) + (sum2 ?? 0) + (sum3 ?? 0);
Run Code Online (Sandbox Code Playgroud)
通过这种方式,语句被"链接"在一起,如使用+所要求的那样
| 归档时间: |
|
| 查看次数: |
15240 次 |
| 最近记录: |