如何在编译/优化后看到 C# 代码?
当我看到《C# 深度剖析》中的示例章节时,我正在阅读有关 yield
关键字的内容:http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx。
第一个代码块利用 yield
关键字来创建一个简单的迭代器。但是,第二个代码块在编译器处理完之后显示了该代码。除此之外,它将 yield
语句分解为状态机。
页面上还可以看到编译器修改代码的其他几个示例。
我的问题是:作者是否真的能够在编译后访问代码,或者他是否推断出代码会是什么样子?
I was reading about the yield
keyword when I came across a sample chapter from C# in Depth: http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx.
The first block of code utilizes the yield
keyword to make a simple iterator. But, the second block of code shows this code after the compiler has had its way with it. Among other things, it has exploded the yield
statement into a state machine.
Several other examples of code being modified by the compiler is evident on the page.
My question is: Was the author actually able to access the code after compilation, or did he infer what it was going to look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 Reflector 来查看,这可能是您最好的选择:
http://reflector.red-gate.com
You can have a look using Reflector, that's probably your best bet:
http://reflector.red-gate.com
作者本人提到:
在同一段落中,标题为高级概述:模式是什么?
The author himself mentioned:
in the same paragraph, titled High level overview: what's the pattern?
可能两者都有。使用 Reflector 对编译后的程序集进行逆向工程非常容易。 C# 语言规范定义了如何编译各种语法糖,是一个公共文档。作者可以使用任何一种方法,也可以混合使用两种方法。
Probably both. It's quite easy to reverse-engineer compiled assemblies using Reflector. And the C# language spec, which defines how various syntactic-sugary things are compiled, is a public document. The author could have used either approach, or a mixture of the two.
查看 ildasm 看一下在编译的 IL 中。
(真的,一旦你的眼睛进去了,这很有趣)
Check out ildasm to take a look at the compiled IL.
(Really, it's good fun once you get your eye in)
.NET CLR 实际上有一种称为 MSIL 的汇编形式,以及汇编器和反汇编器。所以是的,您可以实际编译代码,然后查看确切的编译 CLR 指令。
https://web.archive .org/web/20211020103545/https://www.4guysfromrolla.com/articles/080404-1.aspx
.NET CLR actually has a form of assembly called MSIL, along with an assembler and dissembler. So yes, you can actually compile the code, then see the exact compiled CLR instructions.
https://web.archive.org/web/20211020103545/https://www.4guysfromrolla.com/articles/080404-1.aspx
dotPeek 由 JetBrains
https://www.jetbrains.com/decompiler/
它是免费且易于使用的:)
dotPeek by JetBrains
https://www.jetbrains.com/decompiler/
It's free and easy to use :)