使用表达式树导航并返回拥有属性的对象

时间:2010-07-16 11:57:51

标签: c# .net-3.5 expression-trees

给定一个指向对象图中属性的表达式,我想要检索拥有该图的属性的实例。我一直在努力。当前代码只给我System.InvalidOperationException:Lambda参数不在范围

    [Test]
    public void TestExpression()
    {
        var person = new Person {Address = {Street = "Bank Street"}, Name = "Joe"};

        Expression<Func<Person, object>> exp = p => p.Address.Street;
        Assert.AreEqual("Bank Street", exp.Compile().Invoke(person));

        var owner = GetPropertyOwner(person, exp);
        Assert.AreEqual(owner, person.Address);
    }

    private object GetPropertyOwner<T>(T root, Expression<Func<T, object>> exp)
    {
        if (exp.Body is MemberExpression)
        {
            var member = exp.Body as MemberExpression;
            if (member.Expression is MemberExpression)
            {
                var parentMember = member.Expression as MemberExpression;
                //parent member will be {p.Address}
                //Now I'm trying to reconstruct an expression that I can combile
                var parameterExpression = System.Linq.Expressions.Expression.Parameter(typeof(T), "p");
                var lambdaExpression = System.Linq.Expressions.Expression.Lambda(parentMember, parameterExpression);
                //Next Linethrows  System.InvalidOperationException : Lambda Parameter not in scope
                var found = lambdaExpression.Compile().DynamicInvoke(person);
                return found;
            }
        }

        return new object();
    }

1 个答案:

答案 0 :(得分:2)

ParameterExpression对象通过引用相等而非名称进行比较,因此lambdaExpression所采用的“p”参数与parentMember中使用的参数不同。构建新的lambda时,需要使用相同的ParameterExpression实例。试试:

var parameterExpression = exp.Parameters[0];