我正在使用System.Linq.Expressions

我试图构建一个包含LambdaExpression的简单MemberExpression。如果我使用System.Linq.Expressions API(例如MakeMemberAccess)显式创建MemberExpression,当我在Compil()上调用Compile()时,将收到错误“InvalidOperationExpression变量'x',从范围”引用,但未定义” LambdaExpression。

例如,这是我的代码

Expression<Func<Customer, string>> expression1, expression2, expression3;
Func<Customer, string> fn;
expression1 = (x) => x.Title;
fn = expression1.Compile();//works
fn(c);
MemberExpression m;
m = Expression.MakeMemberAccess(
Expression.Parameter(typeof(Customer), "x"), typeof(Customer).GetProperty("Title"));
expression2 = Expression.Lambda<Func<Customer, string>>(m,
    Expression.Parameter(typeof(Customer), "x"));

m = Expression.Property(Expression.Parameter(typeof(Customer),"x"), "Title");
expression3 = Expression.Lambda<Func<Customer, string>>(m,
    Expression.Parameter(typeof(Customer), "x"));

fn = expression3.Compile();//InvalidOperationExpression variable 'x' referenced from scope '', but it is not defined
fn = expression2.Compile();//InvalidOperationExpression variable 'x' referenced from scope '', but it is not defined

当调用Compile()方法时,expression2和expression3引发异常,但expression1不会; expression1起作用。为什么是这样?当我调用Compile()时,如何创建类似于表达式2、3的MemberExpression并使它们工作(不引发异常)?

谢谢

最佳答案

您将多次创建名为“x”的不同参数。如果您使用单个ParameterExpression,那么它们应该都可以正常工作。

ParameterExpression p = Expression.Parameter(typeof(Customer), "x");
MemberExpression m = Expression.MakeMemberAccess(p,
    typeof(Customer).GetProperty("Title"));
expression2 = Expression.Lambda<Func<Customer, string>>(m, p);

m = Expression.Property(p, "Title");
expression3 = Expression.Lambda<Func<Customer, string>>(m, p);

fn = expression3.Compile();
fn = expression2.Compile();

基本上,参数表达式不与名称匹配-您必须在各处使用相同的表达式。有点痛苦,但是我们去了...

关于c# - MemberExpression : InvalidOperationExpression variable 'x' referenced from scope '' ,,但未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6106283/

10-16 09:00