Retrieving Property name from lambda expression

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

    With C# 7 pattern matching:

    public static string GetMemberName(this Expression expression)
    {
        switch (expression.Body)
        {
            case MemberExpression m:
                return m.Member.Name;
            case UnaryExpression u when u.Operand is MemberExpression m:
                return m.Member.Name;
            default:
                throw new NotImplementedException(expression.GetType().ToString());
        }
    }
    

    Example:

    public static RouteValueDictionary GetInfo(this HtmlHelper html, 
        Expression> action) where T : class
    {
        var name = action.GetMemberName();
        return GetInfo(html, name);
    }
    

    [Update] C# 8 pattern matching:

    public static string GetMemberName(this Expression expression) =>
        expression.Body switch
        {
            MemberExpression m =>
                m.Member.Name,
            UnaryExpression u when u.Operand is MemberExpression m =>
                m.Member.Name,
            _ =>
                throw new    NotImplementedException(expression.GetType().ToString())
        };
    

提交回复
热议问题