Lambda 表达式 Compile() 方法有什么作用? [英] What does Lambda Expression Compile() method do?

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

问题描述

我正在尝试理解 C# 中的 AST.我想知道这个例子中的 Compile() 方法到底做了什么.

I am trying to understand AST in C#. I wonder, what exactly Compile() method from this example does.

// Some code skipped    
Expression<Func<string, int, int, string>> data = Expression.Lambda<Func<string, int, int, string>>( 
        Expression.Call(s, typeof(string).GetMethod("Substring", new Type[] { typeof(int), typeof(int) }), a, b), 
        s, a, b 
    ); 
Func<string, int, int, string> fun = data.Compile(); 

为了防止误解,我理解了 Expression.LambdaExpression.Call 结构.我感兴趣的是 Compile() 方法.它是否以某种方式产生真正的 MSIL?我能看到 MSIL 吗?

To prevent misunderstandings, I understand the Expression.Lambda and Expression.Call constructs. What interests me is the Compile() method. Does it somehow produce real MSIL? Can I see the MSIL?

推荐答案

我感兴趣的是 Compile() 方法.它是否以某种方式产生真正的 MSIL?

What interests me is the Compile() method. Does it somehow produce real MSIL?

是的.Compile 方法在 lambda 主体块上运行访问者,并为每个子表达式动态生成 IL.

Yes. The Compile method runs a visitor over the lambda body block and generates IL dynamically for each subexpression.

如果你有兴趣学习如何自己吐槽 IL,请参阅 这个Hello World"如何使用轻量级 Codegen 的示例.(我注意到,如果您不幸不得不在部分受信任的应用程序域中使用轻量级 Codegen,那么在受限跳过可见性的世界中事情会变得有点奇怪;请参阅 Shawn Farkas 关于这个主题的文章,如果你感兴趣的话.)

If you're interested in learning how to spit IL yourself, see this "Hello World" example of how to use Lightweight Codegen. (I note that if you are in the unfortunate position of having to use Lightweight Codegen in a partially trusted appdomain then things can get a bit weird in a world with Restricted Skip Visibility; see Shawn Farkas's article on the subject if that interests you.)

我能看到 MSIL 吗?

Can I see the MSIL?

是的,但您需要一个特殊的可视化器".我在实现我的部分时用来调试 Compile() 的可视化工具可以在这里下载:

Yes, but you need a special "visualizer". The visualizer I used to debug Compile() while I was implementing my portions of it can be downloaded here:

http://blogs.msdn.com/b/haibo_luo/archive/2005/10/25/484861.aspx

这篇关于Lambda 表达式 Compile() 方法有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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