Retrieving Property name from lambda expression

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

    I recently did a very similar thing to make a type safe OnPropertyChanged method.

    Here's a method that'll return the PropertyInfo object for the expression. It throws an exception if the expression is not a property.

    public PropertyInfo GetPropertyInfo(
        TSource source,
        Expression> propertyLambda)
    {
        Type type = typeof(TSource);
    
        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 (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;
    }
    

    The source parameter is used so the compiler can do type inference on the method call. You can do the following

    var propertyInfo = GetPropertyInfo(someUserObject, u => u.UserID);
    

提交回复
热议问题