System.Linq.Enumerable.Sum() 与直接加法不同的行为背后的逻辑是什么?
var x = 1 + null; // x = null
var y = new int?[]{ 1, null }.Sum(); // y = 1
Sum 忽略空值。我对为什么感兴趣。
public static int? Sum(this IEnumerable<int?> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
int num = 0;
foreach (int? item in source)
{
if (item.HasValue)
num = checked(num + item.GetValueOrDefault());
}
return num;
}