gpt4 book ai didi

c# - MemberExpression : InvalidOperationExpression variable 'x' referenced from scope '' , 但未定义

转载 作者:太空狗 更新时间:2023-10-29 18:16:48 25 4
gpt4 key购买 nike

我正在使用 System.Linq.Expressions

我试图构建一个简单的 LambdaExpression其中包括 MemberExpression .如果我使用 System.Linq.Expressions API(例如 MakeMemberAccess)显式创建 MemberExpression,我将在调用 Compile() 时收到错误“InvalidOperationExpression variable 'x' referenced from scope '', but it is not defined”在 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 不会;表达式 1 有效。为什么是这样?我如何创建一个像表达式 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();

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com