Retrieving Property name from lambda expression

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

    Here is another way to get the PropertyInfo based off this answer. It eliminates the need for an object instance.

    /// 
    /// Get metadata of property referenced by expression. Type constrained.
    /// 
    public static PropertyInfo GetPropertyInfo(Expression> propertyLambda)
    {
        return GetPropertyInfo((LambdaExpression) propertyLambda);
    }
    
    /// 
    /// Get metadata of property referenced by expression.
    /// 
    public static PropertyInfo GetPropertyInfo(LambdaExpression propertyLambda)
    {
        // https://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression
        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));
    
        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));
    
        if(propertyLambda.Parameters.Count() == 0)
            throw new ArgumentException(String.Format(
                "Expression '{0}' does not have any parameters. A property expression needs to have at least 1 parameter.",
                propertyLambda.ToString()));
    
        var type = propertyLambda.Parameters[0].Type;
        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(String.Format(
                "Expression '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));
        return propInfo;
    }
    

    It can be called like so:

    var propertyInfo = GetPropertyInfo((User u) => u.UserID);
    

提交回复
热议问题