如何在表达式中获取值

时间:2014-12-23 09:15:23

标签: c# asp.net asp.net-mvc linq delegates

我有表达式s => s.Application.Id

我想获得Application.Id。

因为表达式可以在下一种情况下变化

s=s.Application.ApplicationType.Id

在这种情况下,我想要Application.ApplicationType.Id

我尝试过使用expression.body.member.name

它给了我Id。

2 个答案:

答案 0 :(得分:1)

您可以使用ExpressionVisitor解析它,它只会记住参数表达式并将其从这样的请求中删除:

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        Expression<Func<Parent, int>> expression = s => s.Application.ID;

        var val = new CustomVisitor().ConvertToString(expression);

        Console.WriteLine("expression is " + val);
    }
}

public class CustomVisitor : ExpressionVisitor
{
    private ParameterExpression _param;

    private Expression _body;

    protected override Expression VisitLambda<T>(Expression<T> node)
    {
        _body = node.Body;
        return base.VisitLambda(node);
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        _param = node;
        return node;
    }

    public string ConvertToString(Expression expression)
    {
        Visit(expression);

        var parameterLength = _param.Name.Length + 1; // cuts name plus dot
        return _body.ToString().Substring(parameterLength);
    }
}

public class Parent
{
    public Application Application {get;set;}
}

public class Application
{
    public int ID {get;set;}
}

以下是DotNetFiddle的工作示例 - https://dotnetfiddle.net/Fmye6z

答案 1 :(得分:0)

无需编译或任何花哨的东西。只需递归地遍历表达式树以组装完整路径。

class Program
{
    static void Main(string[] args)
    {
        string path = GetPropertyName<Test>(x => x.Test2.Application.Id);
    }

    static string GetPropertyName<T>(Expression<Func<T, object>> expression)
    {
        var memberExpression = (MemberExpression)expression.Body;
        return GetMemberExpressionPath(memberExpression);
    }

    static string GetMemberExpressionPath(MemberExpression exp)
    {
        string s = null;

        var rootExp = exp.Expression as MemberExpression;
        if (rootExp != null)
        {
            s = GetMemberExpressionPath(rootExp);
        }

        //var paramExp = exp.Expression as ParameterExpression;
        //if (paramExp != null)
        //{
        //    s = paramExp.Name;
        //}

        return (s != null ? s + "." : "") + exp.Member.Name;
    }

}