PropertyInfo
就像他在回答中所说的那样,我不会使用Reed Copsey
,但仅供参考,您可以使用以下方法提取PropertyInfo
表达式的 :
public PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
{
MemberExpression Exp = null;
//this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
if (GetPropertyLambda.Body is UnaryExpression)
{
var UnExp = (UnaryExpression)GetPropertyLambda.Body;
if (UnExp.Operand is MemberExpression)
{
Exp = (MemberExpression)UnExp.Operand;
}
else
throw new ArgumentException();
}
else if (GetPropertyLambda.Body is MemberExpression)
{
Exp = (MemberExpression)GetPropertyLambda.Body;
}
else
{
throw new ArgumentException();
}
return (PropertyInfo)Exp.Member;
}
对于像这样的复合表达式MyPerson.PersonData.PersonID
,您可以获取子表达式,直到它们MemberExpressions
不再存在为止。
public PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
{
//same body of above method without the return line.
//....
//....
//....
var Result = (PropertyInfo)Exp.Member;
var Sub = Exp.Expression;
while (Sub is MemberExpression)
{
Exp = (MemberExpression)Sub;
Result = (PropertyInfo)Exp.Member;
Sub = Exp.Expression;
}
return Result;
//beware, this will return the last property in the expression.
//when using GetValue and SetValue, the object needed will not be
//the first object in the expression, but the one prior to the last.
//To use those methods with the first object, you will need to keep
//track of all properties in all member expressions above and do
//some recursive Get/Set following the sequence of the expression.
}