Retrieving Property name from lambda expression

前端 未结 21 1692
迷失自我
迷失自我 2020-11-21 11:12

Is there a better way to get the Property name when passed in via a lambda expression? Here is what i currently have.

eg.

GetSortingInfo         


        
21条回答
  •  别跟我提以往
    2020-11-21 11:50

    I was playing around with the same thing and worked this up. It's not fully tested but seems to handle the issue with value types (the unaryexpression issue you ran into)

    public static string GetName(Expression> exp)
    {
        MemberExpression body = exp.Body as MemberExpression;
    
        if (body == null) {
           UnaryExpression ubody = (UnaryExpression)exp.Body;
           body = ubody.Operand as MemberExpression;
        }
    
        return body.Member.Name;
    }
    

提交回复
热议问题