Retrieving Property name from lambda expression

前端 未结 21 1731
迷失自我
迷失自我 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 12:01

    public string GetName(Expression> Field)
    {
        return (Field.Body as MemberExpression ?? ((UnaryExpression)Field.Body).Operand as MemberExpression).Member.Name;
    }
    

    This handles member and unary expressions. The difference being that you will get a UnaryExpression if your expression represents a value type whereas you will get a MemberExpression if your expression represents a reference type. Everything can be cast to an object, but value types must be boxed. This is why the UnaryExpression exists. Reference.

    For the sakes of readability (@Jowen), here's an expanded equivalent:

    public string GetName(Expression> Field)
    {
        if (object.Equals(Field, null))
        {
            throw new NullReferenceException("Field is required");
        }
    
        MemberExpression expr = null;
    
        if (Field.Body is MemberExpression)
        {
            expr = (MemberExpression)Field.Body;
        }
        else if (Field.Body is UnaryExpression)
        {
            expr = (MemberExpression)((UnaryExpression)Field.Body).Operand;
        }
        else
        {
            const string Format = "Expression '{0}' not supported.";
            string message = string.Format(Format, Field);
    
            throw new ArgumentException(message, "Field");
        }
    
        return expr.Member.Name;
    }
    

提交回复
热议问题