How to set properties and nested property's properties with expression

故事扮演 提交于 2019-12-06 04:40:26

Something like this should work:

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!