lak*_*doo 8 .net c# linq generics
我试图总结泛型集合中的值,我使用相同的确切代码在我的代码的其他部分执行此函数但似乎有ulong数据类型的问题?
代码
Items.Sum(e => e.Value);
Run Code Online (Sandbox Code Playgroud)
有以下错误:
错误15以下方法或属性之间的调用不明确:'
System.Linq.Enumerable.Sum<System.Collections.Generic.KeyValuePair<int,ulong>>(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<int,ulong>>, System.Func<System.Collections.Generic.KeyValuePair<int,ulong>,float>)'和'System.Linq.Enumerable.Sum<System.Collections.Generic.KeyValuePair<int,ulong>>(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<int,ulong>>, System.Func<System.Collections.Generic.KeyValuePair<int,ulong>,decimal?>)
public class Teststuff : BaseContainer<int, ulong, ulong>
{
public decimal CurrentTotal { get { return Items.Sum(e => e.Value); } }
public override void Add(ulong item, int amount = 1)
{
}
public override void Remove(ulong item, int amount = 1)
{
}
}
public abstract class BaseContainer<T, K, P>
{
/// <summary>
/// Pass in the owner of this container.
/// </summary>
public BaseContainer()
{
Items = new Dictionary<T, K>();
}
public BaseContainer()
{
Items = new Dictionary<T, K>();
}
public Dictionary<T, K> Items { get; private set; }
public abstract void Add(P item, int amount = 1);
public abstract void Remove(P item, int amount = 1);
}
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 18
Sum()没有返回a的重载,ulong编译器无法决定调用哪些重载.
你可以用演员来帮助它决定:
Items.Sum(e => (decimal)e.Value)
Run Code Online (Sandbox Code Playgroud)
同意Sum()没有返回a的重载,ulong编译器无法决定调用哪些重载.但是,如果你投了很长时间,你可以遇到一个System.OverflowException: Arithmetic operation resulted in an overflow.
相反,您可以创建一个这样的扩展方法:
public static UInt64 Sum(this IEnumerable<UInt64> source)
{
return source.Aggregate((x, y) => x + y);
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必担心转换,它使用本机数据类型添加.
| 归档时间: |
|
| 查看次数: |
4267 次 |
| 最近记录: |