gpt4 book ai didi

.net - 可空类型的 LINQ 聚合行为

转载 作者:行者123 更新时间:2023-12-04 07:12:19 26 4
gpt4 key购买 nike

有人可以解释这里发生了什么吗?为什么这两件事都是真的?

[TestMethod]
public void WhatIsGoingOnHere()
{
List<int?> list = new List<int?> { 1, 2, 3, null, 5, 6 };
Assert.AreEqual(17, list.Sum());

int? singleSum = 1 + 2 + 3 + null + 5 + 6;

Assert.IsNull(singleSum);
}

具体来说,为什么 Sum() 方法不返回“null”?还是 singleSum 不等于 17?

最佳答案

您所看到的是使用 Enumerable.Sum 之间的区别并实际添加自己的值。

这里重要的是null不为零。乍一看你会认为singleSum应该等于 17 但这意味着我们必须为 null 分配不同的语义基于引用的数据类型。事实上,这是一个 int?没有区别 - nullnull并且永远不应该在语义上与数字常量 0 相等.
Enumerable.Sum的实现旨在跳过任何值 null在序列中,这就是为什么您会看到两个测试之间的不同行为。然而,第二个测试正确地返回 null因为编译器足够聪明,知道向 null 添加任何内容 yield null .

这是Enumerable.Sum的实现接受参数 int? :

public static int? Sum(this IEnumerable<int?> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int num = 0;
foreach (int? nullable in source)
{
// As you can see here it is explicitly designed to
// skip over any null values
if (nullable.HasValue)
{
num += nullable.GetValueOrDefault();
}
}
return new int?(num);
}

关于.net - 可空类型的 LINQ 聚合行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3673763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com