Get PropertyInfo of a parameter passed as lambda expression

前端 未结 4 1794
攒了一身酷
攒了一身酷 2021-01-11 14:49

For example, I have a class:

public class Person
{
  public int Id;
  public string Name, Address;
}

and I want to call a method to update

4条回答
  •  失恋的感觉
    2021-01-11 15:37

    Even cleaner IMHO (another variant on @DanielMöller's post)

            /// 
            ///     Gets the corresponding  from an .
            /// 
            /// The expression that selects the property to get info on.
            /// The property info collected from the expression.
            /// When  is null.
            /// The expression doesn't indicate a valid property."
            public static PropertyInfo GetPropertyInfo(this Expression> expression)
            {
                switch (expression?.Body) {
                    case null:
                        throw new ArgumentNullException(nameof(expression));
                    case UnaryExpression unaryExp when unaryExp.Operand is MemberExpression memberExp:
                        return (PropertyInfo)memberExp.Member;
                    case MemberExpression memberExp:
                        return (PropertyInfo)memberExp.Member;
                    default:
                        throw new ArgumentException($"The expression doesn't indicate a valid property. [ {expression} ]");
                }
            }
    

提交回复
热议问题