无论从哪方面来看,我都不是表达式树的专家,我所拥有的代码如下所示:

    int external = 10;
    using(var session = new Session())
    {
       session.Add(new Product { Name = "test1", Price = 20 });
       session.Add(new Product {Name = "test", Price = 10});
       var product = session.Products.Where(p => p.Price == external).FirstOrDefault();
       Assert.Equal(10, product.Price);
    }


Session实现了您希望从LINQ Provider获得的所有IQueryProvider,IQueryable接口。

当我评估表达式树时,一切都会按计划进行,直到我阅读了“ external”的ConstantExpression为止,此时,我对前进的方向一无所知,因为:

      //constant is ConstantExpression for "external" on the right side of the "p.Price == external" expression above.
      var t = constant.GetType(); //evaluates to class called "<>c__DisplayClass2" - with a member named "external" that has the value 10.


问题基本上是..我怎样才能只访问成员“ external”的值-有没有一种方法可以在不使用反射的情况下完成此操作?还是我煮过?我想念什么?

最佳答案

您的表达式捕获了external局部变量,这就是编译器隐式创建匿名类型以包装捕获的变量的原因。等式的右侧部分不是ConstantExpression,实际上是MemberExpression,其Expression属性是ConstantExpression类型的<>c__DisplayClass2

您可以按如下方式访问属性的值:

MemberExpression memberExpr = /* right-hand side of the equality */ as MemberExpression;
ConstantExpression constantExpr = memberExpr.Expression as ConstantExpression;
PropertyInfo prop = memberExpr.Member as PropertyInfo;
object value = prop.GetValue(constantExpr.Value, null);

关于c# - ExpressionTreeVisitor中的ConstantExpression的部分评估,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2529985/

10-10 00:16