我试图了解C#中的AST。我想知道,此示例中的Compile()方法到底是做什么的。

// 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吗?

最佳答案



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

如果您有兴趣学习如何自己吐IL,请参阅this "Hello World" example of how to use Lightweight Codegen。 (我注意到,如果您处于不得不在部分受信任的应用程序域中使用Lightweight Codegen的不幸位置,那么在具有受限跳过可见性的世界中,事情可能会变得有些奇怪;如果您对此感兴趣,请参阅Shawn Farkas's article。)



是的,但是您需要一个特殊的“可视化器”。在实现我的部分代码时用来调试Compile()的可视化工具可在此处下载:

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

关于c# - Lambda Expression Compile()方法有什么作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8127042/

10-13 03:14