Dynamically evaluating a property string with Expressions

前端 未结 2 528
礼貌的吻别
礼貌的吻别 2021-01-05 18:35

How do I build an expression that will fulfill the following goal:

public object Eval(object rootObj, string propertyString)

eg: Eval(pers

2条回答
  •  梦谈多话
    2021-01-05 19:11

    Here's a recursive version of p.s.w.g's code, working with Expressions.

    public Expression Eval(Expression expression, string property)
    {
        var split = property.Split('.');
        if (split.Length == 1)
        {
            return Expression.PropertyOrField(expression, property);
        }
        else
        {
            return Eval(Expression.PropertyOrField(expression, split[0]), property.Replace(split[0] + ".", ""));
        }
    }
    

提交回复
热议问题