如何使用表达式设置属性和嵌套属性的属性

时间:2012-06-07 20:57:02

标签: c# reflection lambda expression-trees

我用Google搜索了这个问题并搜索了SO。有很多解决方案,所有这些(我发现)都没有完成。你可以帮助我设置一个类的属性及其嵌套属性的属性,由lambda使用Reflection选择吗?

public class Parent
{
    public class Child
    { 
        public int Id { get; set; }
    }

    public string Name { get; private set; }
    public int Number {get; private set; }
    public Child Nested { get; set; }

    public Parent()
    {
        Nested = new Child();
    }

    public Test Set<TValue>(Expression<Func<???> func, TValue value)
    {
        // find the property name from expression
        // set the property by value
        return this;
    }
}

在消费者中,我希望能够:

Parent t = new Parent();
t.Set<int>(t => t.Number, 6)
 .set<string>(t => t.Name, "something")
 .Set<int>(t => t.Nested.Id, 25);

1 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

public class Parent
{
    public Parent Set<TValue>(Expression<Func<Parent, TValue>> func, TValue value)
    {
        MemberExpression mex = func.Body as MemberExpression;
        if(mex == null) throw new ArgumentException();

        var pi = mex.Member as PropertyInfo;
        if(pi == null) throw new ArgumentException();

        object target = GetTarget(mex.Expression);
        pi.SetValue(target, value, null);
        return this;
    }

    private object GetTarget(Expression expr)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.Parameter:
                return this;
            case ExpressionType.MemberAccess:
                MemberExpression mex = (MemberExpression)expr;
                PropertyInfo pi = mex.Member as PropertyInfo;
                if(pi == null) throw new ArgumentException();
                object target = GetTarget(mex.Expression);
                return pi.GetValue(target, null);
            default:
                throw new InvalidOperationException();
        }
    }
}