1

类似于问题How can I get property name strings used in a Func of T

假设我有一个像这样存储在一个名为“getter”的变量中的 lambda 表达式

Expression<Func<Customer, string>> productNameSelector =
    customer => customer.Product.Name;

如何从中提取字符串“Product.Name”?

我现在用

var expression = productNameSelector.ToString();
var token = expression.Substring(expression.IndexOf('.') + 1);

但我想找到一种更可靠的方法;-)

4

2 回答 2

2

您的表达式的表达式树如下所示:

           .
          / \
         .   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));
}
于 2012-06-08T10:02:01.580 回答
1

如果你有一个表达式,你可以使用 ToString 方法来提取字符串表示:

Expression<Func<Customer, string>> productNameSelector = 
    customer => customer.Product.Name;

var expression = productNameSelector.ToString();
var token = expression.Substring(expression.IndexOf('.') + 1);
于 2012-06-08T09:19:02.387 回答