如何在表达式中获取值

本文关键字:获取 表达式 | 更新日期: 2023-09-27 18:35:15

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

我想 Application.Id。

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

s=s.Application.ApplicationType.Id

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

我试过 expression.body.member.name

它给了我 Id。

如何在表达式中获取值

您可以使用 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

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

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;
    }
}