简体   繁体   English

在运行时将身份(e => e)构造为表达式树

[英]Construct identity (e => e) at run time as expression tree

I need to create identity expression tree at run-time that just returns the parameter that it receives. 我需要在运行时创建身份表达树,该树只返回它收到的参数。

At compile time I could use the lambda e => e as expression tree, but I need that transformation at run-time. 在编译时,我可以将lambda e => e用作表达式树,但是我需要在运行时进行该转换。 I'm looking for code similar to how expression tree for num => num < 5 is constructed in MSDN Expression Trees article. 我正在寻找类似于MSDN Expression Trees文章中如何构造num => num < 5 表达式树的代码

This will do it: 这样做:

var param = Expression.Parameter(typeof(int), "e");
var body = param;
var lambda = Expression.Lambda<Func<int, int>>(body, param);

Output of lambda.ToString() : lambda.ToString()输出:

e => e

Note that you need to give e a type (in this case it's an int). 请注意,您需要给e一个类型(在这种情况下,它是一个int)。


Pre-edit note: 编辑前注意事项:

What you've written ( e => e ) is actually already an expression tree (if defined as an Expression<T> , that is). 您所写的( e => e )实际上已经是一个表达式树(如果定义为Expression<T> )。 However, it's likely you're wanting to use the factory methods to build the tree. 但是,您可能想使用工厂方法来构建树。

e => e . e => e That's it. 而已。

It will need to be typed, of course, so eg Expression<Func<int, int>> intTree = e => e; 当然,将需要键入它,例如Expression<Func<int, int>> intTree = e => e; for ints, Expression<Func<string, string>> stringTree = e => e; 对于整数, Expression<Func<string, string>> stringTree = e => e; for strings, and so on. 字符串等。

Now you've got the tree from the lambda, you can examine it or do whatever else you want the tree for: 现在,您已经从lambda中获得了树,您可以对其进行检查或执行其他您想要的树操作:

Console.WriteLine(intTree.Parameters[0].Name); // "e"
Console.WriteLine(intTree.CanReduce); // false
Func<int, int> intIdentityFunction = intTree.Compile();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM