MemberExpression:从范围''引用的InvalidOperationExpression变量'x',但未定义

时间:2011-05-24 05:55:26

标签: c# linq expression-trees

我正在使用System.Linq.Expressions

我试图构建一个包含LambdaExpression的简单MemberExpression。如果我使用System.Linq.Expressions API(例如MakeMemberAccess)显式创建MemberExpression,我将在调用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

expression2和expression3在调用Compile()方法时抛出异常,但是expression1没有; expression1有效。为什么是这样?如何在表达式2,3中创建一个MemberExpression,并在调用Compile()时让它们工作(不抛出异常)?

由于

1 个答案:

答案 0 :(得分:15)

您正在多次创建名为“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();

基本上参数表达式与名称不匹配 - 你必须在任何地方使用相同的表达式。这有点痛苦,但我们去了......