Compile expression that requires a parameter

2019-05-07 09:57发布

问题:

Ok, I am sure this is simple, but I am having a senior moment.

I have a simple BinaryExpression (greaterthan) the left side is a ParameterExpression and the right side is a ConstantExpression I want to compile this expression to a func that I can call and pass a parameter to...

var func = ...something with my exp....

bool result = func(myValue);

Thanks to Hasan, I modified his answer to my needs...

var func = Expression.Lambda<Func<int,bool>>(myExpr, (ParameterExpression)myExpr.left).Compile();

回答1:

var param = Expression.Parameter(typeof(int));
var value = Expression.Constant(3);
var body = Expression.GreaterThan(param, value);
var checkValue = Expression.Lambda<Func<int, bool>>(body, param).Compile();

Console.WriteLine(checkValue(4));
Console.WriteLine(checkValue(2));