public class Foo
{
public ushort Weight { get; }
}Run Code Online (Sandbox Code Playgroud)
public class Bar<T> : IEnumerable where T : Foo
{
private Collection<T> _contents;
...
public ulong TotalWeight { get { return _contents.Sum(a => a.Weight); } }
}Run Code Online (Sandbox Code Playgroud)
我期望总数加起来超过一个ushort的最大值.
我收到了一个Intellisense错误:"模糊调用",其中包含一个不包含ushort或ulong的数字类型列表.我不确定它想要什么.
我也尝试过使用Select(来自这篇文章),如下:
_contents.Select(a => a.Weight).Sum()Run Code Online (Sandbox Code Playgroud)
但Intellisense抱怨它无法解决Sum方法并列出了一堆候选人,这些候选人也不包括ushort或ulong.再说一遍,我不确定它想要什么.
如果这真的很新鲜,我道歉,我只是不明白Intellisense告诉我的是什么.
没有Sum过载适用于ushort序列或一般序列和投影ushort.最简单的方法是简单地转换为long:
return _contents.Sum(a => (long) a.Weight);
Run Code Online (Sandbox Code Playgroud)
这也将缓解溢出问题.请注意,使用ulong任何一个都没有过载.如果你有足够的ushort值溢出long,它可能需要一段时间才能添加它们:)
| 归档时间: |
|
| 查看次数: |
1703 次 |
| 最近记录: |