[英]Evaluation Expression<Func<>> with variables
Our Company is having a Framework which requests Queries as Expression(Func(T, bool)) where T is the given Type ob the Buiniess Object.我们公司有一个框架,它请求作为 Expression(Func(T, bool)) 的查询,其中 T 是 Buiniess 对象的给定类型。
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 属性给出以下结果
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.您想要做的是替换任何左侧为
ConstantExpression
类型的MemberExpression
,使用反射来获取值。 This is what ExpressionVisitor
is built for.这就是
ExpressionVisitor
目的。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.