This is all freely available in MiscUtil. The Operator
class provides access to generic arithmetic; and there are generic implementations (as extension methods) of Sum
, Average
, etc - and works with any type with suitable operators in addition to the primitives. So for example, you could use Sum with of Complex<T>
, etc.
Note that it currently uses .NET 3.5; I did have a 2.0 version somewhere, but it isn't as tested....
A simplified example of sum is shown in the usage document:
public static T Sum<T>(this IEnumerable<T> source)
{
T sum = Operator<T>.Zero;
foreach (T value in source)
{
if (value != null)
{
sum = Operator.Add(sum, value);
}
}
return sum;
}
Although IIRC the actual implementation has a bit more...
As an aside, note that dynamic
(in .NET 4.0 / C# 4.0) supposedly supports operators, but we'll have to wait for the beta to see what it does. From my previous looks at dynamic
in the CTP, I expect it to be a bit slower than the MiscUtil code, but we shall see.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…