Lambda表达式树解析 [英] Lambda Expression Tree Parsing

查看:140
本文介绍了Lambda表达式树解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在项目中使用Lambda表达式来映射到第三方查询API.所以,我要手工解析表达式树.

I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand.

如果我输入如下lambda表达式:

If I pass in a lambda expression like:

p => p.Title == "title"

一切正常.

但是,如果我的lambda表达式如下:

However, if my lambda expression looks like:

p => p.Title == myaspdropdown.SelectedValue

使用.NET调试器,我看不到该功能的实际值.相反,我看到的是这样的东西:

Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like:

p => p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)

有什么作用?当我尝试将表达式的右侧作为字符串获取时,得到的是(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)而不是实际值. 如何获取实际值?

What gives? And when I try to grab the right side of the expression as a string, I get (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue) instead of the actual value. How do I get the actual value?

推荐答案

请记住,当您将lambda表达式作为表达式树来处理时,您没有可执行代码.相反,您有一棵表达元素树,它构成了您编写的表达.

Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote.

Charlie Calvert有一篇不错的帖子对此进行详细讨论.包括使用表达式可视化工具调试表达式的示例.

Charlie Calvert has a good post that discusses this in detail. Included is an example of using an expression visualiser for debugging expressions.

在您的情况下,要获取等式表达式右侧的值,您需要创建一个新的lambda表达式,将其编译然后调用.

In your case, to get the value of the righthand side of the equality expression, you'll need to create a new lambda expression, compile it and then invoke it.

我已经整理了一个简单的例子-希望它能满足您的需求.

I've hacked together a quick example of this - hope it delivers what you need.

public class Class1
{
    public string Selection { get; set; }

    public void Sample()
    {
        Selection = "Example";
        Example<Book, bool>(p => p.Title == Selection);
    }

    public void Example<T,TResult>(Expression<Func<T,TResult>> exp)
    {
        BinaryExpression equality = (BinaryExpression)exp.Body;
        Debug.Assert(equality.NodeType == ExpressionType.Equal);

        // Note that you need to know the type of the rhs of the equality
        var accessorExpression = Expression.Lambda<Func<string>>(equality.Right);
        Func<string> accessor = accessorExpression.Compile();
        var value = accessor();
        Debug.Assert(value == Selection);
    }
}

public class Book
{
    public string Title { get; set; }
}

这篇关于Lambda表达式树解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆