You need a separate line to retrieve a member, where the input expression is a Unary expression.
Just changed it from VB.Net, so it can be a little disconnected - let me know if I need to make any minor changes:
public string GetCorrectPropertyName<T>(Expression<Func<T, Object>> expression) { if (expression.Body is MemberExpression) { return ((MemberExpression)expression.Body).Member.Name; } else { var op = ((UnaryExpression)expression.Body).Operand; return ((MemberExpression)op).Member.Name; } }
VB Version:
Public Shared Function GetCorrectPropertyName(Of T) _ (ByVal expression As Expression(Of Func(Of T, Object))) As String If TypeOf expression.Body Is MemberExpression Then Return DirectCast(expression.Body, MemberExpression).Member.Name Else Dim op = (CType(expression.Body, UnaryExpression).Operand) Return DirectCast(op, MemberExpression).Member.Name End If End Function
Note that the input expression does not necessarily return a string - this limits only the reading of properties that return strings.
Jon Egerton Sep 14 '12 at 8:19 2012-09-14 08:19
source share