MemberExpression: InvalidOperationExpression variable 'x' referenced from scope '', but it is not defined

前端 未结 1 1283
面向向阳花
面向向阳花 2021-01-05 01:08

I\'m using System.Linq.Expressions

I was attempting to build a simple LambdaExpression that includes a MemberExpression. If I create the MemberExpression explicitly

相关标签:
1条回答
  • 2021-01-05 01:30

    You're creating different parameters called "x" several times. If you use a single ParameterExpression, it should all work fine.

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

    Basically parameter expressions aren't matched by name - you've got to use the same one everywhere. It's a bit of a pain, but there we go...

    0 讨论(0)
提交回复
热议问题