I need to call a lambda from a Linq.Expression. I know I can get some method info from the lambda like this:
Func<double, double> square = x => x * x;
MethodInfo mInfo = square.Method;
But that MethodInfo requires a System.RuntimeServices.Closure first argument. Since I'm using .NET Core, that class is internal to System.Linq.Expressions. Even when an instance of that class is created using reflection, I cannot call square from a System.Linq.Expression.
Is there any workaround for this? I'm writing a simple formula evaluator, but I need lambdas for implementing thinks like predicate logic, Newton-Raphson, etc.
Updated:
This code does not work:
static void Main(string[] args) =>
Console.WriteLine(DoubleIt()(4));
static double CallAndDouble(Func<double, double> f, double x)
{
return f(x) + f(x);
}
static Func<double, double> DoubleIt()
{
var input = Expression.Parameter(typeof(double), "x");
var call = Expression.Call(typeof(Program).GetMethod(nameof(CallAndDouble)),
CreateLambda(), input);
return Expression.Lambda<Func<double, double>>(call, input).Compile();
}
static Expression CreateLambda()
{
var input = Expression.Parameter(typeof(double), "x");
var mult = Expression.Multiply(input, input);
return Expression.Lambda<Func<double, double>>(mult, input);
}
In actual code, I'll have some library functions taking lambdas as arguments (like the CallAndDouble from the above code).
Solved by @canton7. Just a typo: I was missing the BindingFlags.