MemberExpression:InvalidOperationExpression变量'x'引用自s



我使用的是System。林克。表达式

我试图构建一个包含MemberExpression的简单LambdaExpression。如果我使用System显式创建MemberExpression。林克。表达式API(例如MakeMemberAccess),当我对LambdaExpression调用Compile()时,我将获得错误"InvalidOperationExpression变量"x"从作用域"引用,但未定义它"。

例如,这是我的代码

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();

基本上,参数表达式不按名称匹配——您必须在任何地方使用相同的参数表达式。这有点痛苦,但我们开始。。。

相关内容

  • 没有找到相关文章

最新更新