局部变量和表达式树 [英] Local variable and expression trees

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

问题描述

我在C#中学习表达式树

I am learning expression trees in C#.

我现在坚持了一段时间:

I am stuck now for a while:

string filterString = "ruby";
Expression<Func<string, bool>> expression = x => x == filterString;

如何通过构建这个代码体现在哪里?没有样品如何捕获的局部变量。这一个是容易的:

How can I construct this expression by code? There is no sample how to capture a local variable. This one is easy:

Expression<Func<string, bool>> expression = x => x == "ruby";

这将是:

ParameterExpression stringParam = Expression.Parameter(typeof(string), "x");
Expression constant = Expression.Constant("ruby");
BinaryExpression equals = Expression.Equal(stringParam, constant);
Expression<Func<string, bool>> lambda1 =
    Expression.Lambda<Func<string, bool>>(
        equals,
        new ParameterExpression[] { stringParam });



调试器打印为(X =系列> X == filterString)以下内容:

The debugger prints the following for (x => x == filterString) :

{X =>(X = =
值(Predicate.Program + LT;> c__DisplayClass3).filterString)}

{x => (x == value(Predicate.Program+<>c__DisplayClass3).filterString)}

感谢您对这个话题脱落一些轻。

Thanks for shedding some light on this topic.

推荐答案

捕获一个局部变量被提升局部变量实际执行到的实例的编译器生成的类的变量。 C#编译器创建在适当的时候额外类的新实例,并改变任何访问局部变量到相关实例的实例变量的访问。

Capturing a local variable is actually performed by "hoisting" the local variable into an instance variable of a compiler-generated class. The C# compiler creates a new instance of the extra class at the appropriate time, and changes any access to the local variable into an access of the instance variable in the relevant instance.

所以表达式树则需要在该实例中的一个字段的访问 - 和实例本身通过常量表达式

So the expression tree then needs to be a field access within the instance - and the instance itself is provided via a ConstantExpression.

有关工作如何创建表达式树通常是创造一个lambda表达式类似的东西,再看看在反射器生成的代码,把优化级别下来,让反射不将其转换回拉姆达的最简单方法表达式。

The simplest approach for working how to create expression trees is usually to create something similar in a lambda expression, then look at the generated code in Reflector, turning the optimization level down so that Reflector doesn't convert it back to lambda expressions.

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

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