private delegate T MyFunc<T>(int i);
private static double SumNumber(int i, int n, MyFunc<double> func)
{
double sum = 0.0;
for (int j = i; i <= n; j++)
{
sum += func(j);
}
return sum;
}
private static Vector SumVector(int i, int n, MyFunc<Vector> func)
{
Vector sum = new Vector(0.0, 0.0);
for (int j = i; i <= n; j++)
{
sum += func(j);
}
return sum;
}
This is a program to calculate sum of MyFunc(j) where j is i to n.
I tried to use interface like:
interface IAddable<T>
{
static T operator +(T x, T y);
}
but it didn’t work.
So what should I do?
Firstly, note that in many ways the non-generic overload version is simpler. Generics do not support operators, nor do interfaces.
Indeed, if there are
Summethods available for your types (perhaps via extension methods onIEnumerable<T>) the caller could use simply:where
projectionis the moral equivalent offunc.For doing it your way, what you might try first is
dynamic:otherwise, there are some tricks you can do to fake generic operators (see MiscUtil), or you could pass in the accumulator method (i.e.
Func<T,T,T> add) as a parameter.