gpt4 book ai didi

c# - Collection.Sum(a => a.ushortProperty) 到 ulong

转载 作者:太空狗 更新时间:2023-10-30 00:56:42 25 4
gpt4 key购买 nike

public class Foo
{
public ushort Weight { get; }
}
public class Bar<T> : IEnumerable where T : Foo
{
private Collection<T> _contents;
...
public ulong TotalWeight { get { return _contents.Sum(a => a.Weight); } }
}

我希望总数加起来超过 ushort 的最大值。

我收到 Intellisense 错误:“调用不明确”,其中包含不包括 ushort 或 ulong 的数字类型列表。我不确定它想要什么。

我也试过使用 Select(来自 this post ),如下:

_contents.Select(a => a.Weight).Sum()

但 Intellisense 提示它无法解析 Sum 方法并列出了一堆也不包括 ushort 或 ulong 的候选方法。同样,我不确定它想要什么。

如果这真的很新,我很抱歉,我只是不明白 Intellisense 告诉我的是什么。

最佳答案

没有 Sum适用于 ushort 序列或一般序列的重载以及对 ushort 的投影。最简单的方法是简单地转换为 long:

return _contents.Sum(a => (long) a.Weight);

这也将缓解溢出问题。请注意,也没有使用 ulong 的重载。如果您有足够的 ushort 值来溢出 long,则可能需要一段时间才能将它们加起来 :)

关于c# - Collection<T>.Sum(a => a.ushortProperty) 到 ulong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060149/

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