Retrieving Property name from lambda expression

前端 未结 21 2030
迷失自我
迷失自我 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:41

    I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

    public static RouteValueDictionary GetInfo(this HtmlHelper html, Expression> action) where T : class
    {
        var expression = (MemberExpression)action.Body;
        string name = expression.Member.Name;
    
        return GetInfo(html, name);
    }
    

    And then call it like so.

    GetInfo((User u) => u.UserId);
    

    and voila it works.

提交回复
热议问题