如何以编程方式解析和修改 C# 代码
我想做的是阅读 C# 代码,解析它,插入一些方法调用,最后编译它。
是否可以将 C# 源代码(字符串列表)转换为 CodeDOM 对象?
What I want to do is to read C# code, parse it, insert some method calls and compile it finally.
Is it possible to convert C# source code (a list of strings) to CodeDOM objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个非常古老的问题,但值得注意的是,接受的答案不再适用。 Microsoft 最近的 Roslyn 项目明确旨在公开编译器在静态过程中获得的有关代码库的所有知识。分析它,并通过托管 API 公开所有这些信息供您利用。它适用于 VB 和 C#。
由于您想要使用静态分析信息,因此您需要
Microsoft.CodeAnalysis
NuGet 包(C# 所需的内容位于Microsoft.CodeAnalysis.CSharp
命名空间下),并且有时位于 文档中的示例和演练页面。This is a really old question, but is worth noting that the accepted answer no longer applies. Microsoft's recent Roslyn project is explicitly aimed at exposing all the knowledge the compiler gains about your codebase in the process of statically analyzing it, and exposing all this information through managed APIs for you to leverage. It is available for both VB and C#.
Since you want to consume static analysis information, you'll need the
Microsoft.CodeAnalysis
NuGet package (the stuff you need for C# is under theMicrosoft.CodeAnalysis.CSharp
namespace) and some time at the samples and walkthroughs page in the docs.使用核心 .NET Framework 无法直接执行此操作。您需要使用第三方或附加工具,例如:
It is not directly possible to do this with the core .NET Framework. You need to use third party or add-on tools, for example:
尝试Linq over C#。太棒了。
Try Linq over C#. It's wonderful.
尝试 Mono.Cecil
Try Mono.Cecil
如果您希望能够解析 C# 源代码(或各种其他语言)并对其进行任意分析和转换,请查看我们的 DMS 软件重组工具包。
DMS 具有完整的 C# 前端,为解析的代码构建完整的抽象语法树(但不是 CodeDom),提供完整的程序 API 用于遍历/检查/更改 AST。修改树后,DMS 可以重新生成与修改后的树相对应的源代码,无论是在保真模式下尝试保留原始间距,还是在漂亮打印模式下应用您可以完全控制的漂亮打印样式。注释会正确保留在重新生成的源中。
此外,DMS 提供源代码级模式匹配和转换(例如,您可以编写“x=x+1 ==> x++”,而不是编码所有要验证的遍历树,破解树以更改.) 请参阅有关程序转换的文章,了解为什么这要少得多工作..
If you want the ability to parse, and carry out arbitrary analyses and transformations on C# source code (or a variety of other languages), check out our The DMS Software Reengineering Toolkit.
DMS has a full C# front end, builds complete abstract syntax trees for parsed code (but not a CodeDom), provides a full procedural API for walking/checking/changing the ASTs. After revising the tree, DMS can regenerate source code corresponding to the modified tree, either in fidelity mode where it tries to preserve the original spacing, or prettyprint mode where it applies a prettyprint style that you can control completely. Comments are retained in the regenerated source properly.
In addition, DMS provides source-level pattern matching and transformation (e.g, you can write "x=x+1 ==> x++" instead of coding all the walk-around-tree-to-verify, hack the tree to change.) See writeup on program transformations to understand what why this is a lot less work..
CSharpCodeProvider 可能就是您要找的。
The CSharpCodeProvider might be what you're looking for.