Dynamically evaluating a property string with Expressions

前端 未结 2 511
礼貌的吻别
礼貌的吻别 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:19

    It sounds like you're looking for something like this:

    public object Eval(object root, string propertyString)
    {
        var propertyNames = propertyString.Split('.');
        foreach(var prop in propertyNames)
        {
            var property = root.GetType().GetProperty(prop);
            if (property == null)
            {
                throw new Exception(...);
            }
    
            root = property.GetValue(root, null);
        }
    
        return root;
    }
    

    To create an Expression use this:

    public Expression Eval(object root, string propertyString)
    {
        var propertyNames = propertyString.Split('.');
        ParameterExpression param = Expression.Parameter(root.GetType, "_");
        Expression property = param;
        foreach(var prop in propertyName)
        {
            property = Expression.PropertyOrField(property, prop);
        }
    
        return Expression.Lambda(property, param);
    }
    

提交回复
热议问题