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

c# expression-trees linq

我正在使用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

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

谢谢

一般承认的答案

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

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




许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因