Supposing I want to use the addition operator (+) as a delegate, how would I pass that to a method?
Looking for something similar to Python's operator.add.
e.g., instead of
var center = _drawingPoly.Aggregate((a, b) => a + b)/_drawingPoly.Count;
I'd want to write something like:
var center = _drawingPoly.Aggregate(operator+)/_drawingPoly.Count;
(FYI, + is overloaded here)
There's nothing built-in, but you could do it using expression trees:
public static Func<T, T, T> OpAdd<T>()
{
var param1Expr = Expression.Parameter(typeof(T));
var param2Expr = Expression.Parameter(typeof(T));
var addExpr = Expression.Add(param1Expr, param2Expr);
var expr = Expression.Lambda<Func<T, T, T>>(addExpr, param1Expr, param2Expr);
return expr.Compile();
}
which you can then use like:
var center = _drawingPoly.Aggregate(OpAdd<int>())/_drawingPoly.Count;
unfortunately this approach isn't type-safe, and you'll probably want to cache the resulting delegates that are created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With