gpt4 book ai didi

c# - Lambda 表达式 Compile() 方法有什么作用?

转载 作者:IT王子 更新时间:2023-10-29 04:09:06 26 4
gpt4 key购买 nike

我正在尝试理解 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 吗?

最佳答案

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

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

如果您有兴趣学习如何自己吐 IL,请参阅 this "Hello World" example of how to use Lightweight Codegen . (我注意到,如果您不幸地不得不在部分受信任的应用程序域中使用轻量级代码生成器,那么在具有 Restricted Skip Visibility 的世界中,事情可能会变得有点奇怪;如果您感兴趣,请参阅关于该主题的 Shawn Farkas's article。)

Can I see the MSIL?

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

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com