2014-01-09 22 views
7

我想总结一个泛型集合中的值,我已经使用相同的确切代码在我的其他代码中执行此功能,但它似乎有一个问题数据类型为ulong在LINQ中使用求和方法

代码

Items.Sum(e => e.Value); 

有以下错误:

Error 15 The call is ambiguous between the following methods or properties: ' 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>) ' and ' 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); 
} 

回答

16

Sum()没有超载,返回一个ulong,编译器不能决定哪些该做的重载存在呼叫。

你能帮助它与投决定:

Items.Sum(e => (decimal)e.Value) 
+0

谢谢我只是将所有的超标改为十进制,我会尽快接受这个计时器。 – lakedoo

+1

@lakedoo:请注意,如果您更改“值”的类型,则不需要投射。另外,你确定你不想“长”吗? – SLaks

+0

好点,是的,我很长一段时间似乎没有任何问题。再次感谢! – lakedoo

8

同意关于Sum()没有超载,返回一个ulong,编译器不能决定其确实存在调用重载的。但是,如果你投一个长期可以运行到一个System.OverflowException: Arithmetic operation resulted in an overflow.

相反,你可以创建一个扩展方法是这样的:

public static UInt64 Sum(this IEnumerable<UInt64> source) 
{ 
    return source.Aggregate((x, y) => x + y); 
} 

这样,你就不必担心铸造,它采用原生数据类型添加。