1

質問に似ています T の Func で使用されるプロパティ名の文字列を取得するにはどうすればよいですか

「getter」という変数に、このように保存されたラムダ式があるとしましょう

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

Expression がある場合は、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 に答える