你表達的表達式樹看起來是這樣的:
.
/\
. Name
/\
customer Product
如您所見,沒有代表Product.Name
的節點。但是你可以使用遞歸和建立自己的字符串:
public static string GetPropertyPath(LambdaExpression expression)
{
return GetPropertyPathInternal(expression.Body);
}
private static string GetPropertyPathInternal(Expression expression)
{
// the node represents parameter of the expression; we're ignoring it
if (expression.NodeType == ExpressionType.Parameter)
return null;
// the node is a member access; use recursion to get the left part
// and then append the right part to it
if (expression.NodeType == ExpressionType.MemberAccess)
{
var memberExpression = (MemberExpression)expression;
string left = GetPropertyPathInternal(memberExpression.Expression);
string right = memberExpression.Member.Name;
if (left == null)
return right;
return string.Format("{0}.{1}", left, right);
}
throw new InvalidOperationException(
string.Format("Unknown expression type {0}.", expression.NodeType));
}
這就是我期待的那種解決方案!在我的項目中對此進行了測試,它的功能如同一種魅力! –