Our Company is having a Framework which requests Queries as Expression(Func(T, bool)) where T is the given Type ob the Buiniess Object.
I need to write an Provider for this and what to evaluate the Content of the Expression
If i have Queries like:
Expression<Func<Person, bool>> expr;
expr = (p) => p.Name == "Smith";
this is no Problem, then I can Use the Body Property of the Expression giving the following Result
Body = {(p.Name == "Smith")}
If i use Variables like this:
Expression<Func<Person, bool>> expr;
string nameToFind = "Smith";
expr = (p) => p.Name == name;
I get the following Result:
Body = {(p.Name == value(TestConsole.Program+<>c__DisplayClass0_0).nameToFind)}
What I want is the have in this case the Variables Value in the parsed Expression like in the first example without variables.
Is ths possible? I would be very greatful for an example or hint
What you want to do is replace any MemberExpression
that has a left hand side of type ConstantExpression
, using reflection to get the value. This is what ExpressionVisitor
is built for.
public class Simplify : ExpressionVisitor{
protected override Expression VisitMember(MemberExpression node){
var expr = Visit(node.Expression);
if (expr is ConstantExpression c){
if (node.Member is PropertyInfo prop)
return Expression.Constant(prop.GetValue(c.Value), prop.PropertyType);
if (node.Member is FieldInfo field)
return Expression.Constant(field.GetValue(c.Value), field.FieldType);
}
return node.Update(expr);
}
}
expr = new Simplify().Visit(expr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.