Apply MemberExpression to an object to retrieve Pr

2019-07-10 04:11发布

I am trying to write a generic function that takes a MemberExpression and an object and returns the value of the Property defined in the member expression.

Here's an example of the code to get the Property name.

public static TProperty GetPropertyName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, TModel model)
{
    if (expression.Body is MemberExpression)
    {
        return ((MemberExpression)expression.Body).Member.Name;
    }
    else
    {
        var op = ((UnaryExpression)expression.Body).Operand;
        return ((MemberExpression)op).Member.Name;
    }
}

But I want to retrieve the value of the property from the model:

public static string GetPropertyValue<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, TModel model)
{
    if (expression.Body is MemberExpression)
    {
        // how do I apply the expression.Body to get the value of the property from model??

    }
    else
    {
        var op = ((UnaryExpression)expression.Body).Operand;
        return ((MemberExpression)op).Member.Name;
    }
}

The way I call this function is:

GetPropertyValue<ObjectModel,bool>(m => m.somebool, m);

标签: c# linq
1条回答
乱世女痞
2楼-- · 2019-07-10 04:39

MemberExpression refers to MemberInfo, which will be PropertyInfo in case of property expression:

static class MemberExpressionHelper
{
    public static TProperty GetPropertyValue<TModel, TProperty>(TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        // case with `UnaryExpression` is omitted for simplicity
        var memberExpression = (MemberExpression)expression.Body;

        var propertyInfo = (PropertyInfo)memberExpression.Member;
        return (TProperty)propertyInfo.GetValue(model);
    }
}

Besides, it is more natural to swap parameters (first is model, second is expression). As a side effect, this allows compiler to infer type arguments:

var bar = MemberExpressionHelper.GetPropertyValue(foo, _ => _.Bar);
查看更多
登录 后发表回答