Generic method to get property values with Linq Expression and reflection

后端 未结 2 1283
南旧
南旧 2021-01-27 00:23

Dear Gods of Reflection

I would like to have a generic GetValue method that can return the following property values given the following

相关标签:
2条回答
  • 2021-01-27 00:45

    The problem is here:

    if (response != null)
    {
       var expr = (MemberExpression)propertyExpression.Body;
       var prop = (PropertyInfo)expr.Member;
       return (T)prop.GetValue(response);
    }
    

    This only works if your expression references a property directly, otherwise propertyExpression.Body will not be a MemberExpression and you'll get a run-time cast error. The three that don't work do not reference a property directly - the first two reverence a method on top of a property (the indexer) and the last references a nested property.

    Since all you want is the value of the expression, though, I think you can just do:

    if (response != null)
    {
       Func<TEntity, T> func = propertyExpression.Compile();  
       return func(response);
    }
    

    If you intended to do other things with the expression (like get the name of the property), then you'll need to decide if you want to support expressions that don't reference a property directly and add handlers for that.

    0 讨论(0)
  • 2021-01-27 00:45

    You can do it simply by Executing your Lambda expression:

            if (response != null)
            {
                return propertyExpression.Compile().Invoke(response);
            }
    
    0 讨论(0)
提交回复
热议问题