简体   繁体   English

如何以编程方式解析和修改C#代码

[英]How to programmatically parse and modify C# code

What I want to do is to read C# code, parse it, insert some method calls and compile it finally. 我想要做的是读取C#代码,解析它,插入一些方法调用并最终编译它。

Is it possible to convert C# source code (a list of strings) to CodeDOM objects? 是否可以将C#源代码(字符串列表)转换为CodeDOM对象?

It is not directly possible to do this with the core .NET Framework. 使用核心.NET Framework无法直接执行此操作。 You need to use third party or add-on tools, for example: 您需要使用第三方或附加工具,例如:

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. 微软最近的Roslyn项目明确旨在揭示编译器在静态分析代码库过程中获得的所有知识,并通过托管API公开所有这些信息,以便您利用。 It is available for both VB and C#. 它适用于VB和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 the Microsoft.CodeAnalysis.CSharp namespace) and some time at the samples and walkthroughs page in the docs. 由于您希望使用静态分析信息,因此您需要Microsoft.CodeAnalysis NuGet包(C#所需的内容在Microsoft.CodeAnalysis.CSharp命名空间下),并且需要一些时间在文档中的示例和演练页面。

Try Linq over C# . 试试Linq而不是C# It's wonderful. 太棒了。

试试Mono.Cecil

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 . 如果您想要解析C#源代码(或各种其他语言)的任意分析和转换,请查看我们的DMS软件再造工具包

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. DMS具有完整的C#前端,为解析的代码(但不是CodeDom)构建完整的抽象语法树,为步行/检查/更改AST提供完整的过程API。 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. 在修改树之后,DMS可以重新生成与修改后的树相对应的源代码,可以是保真模式,它可以保留原始间距,也可以是漂亮印刷模式,它可以应用可以完全控制的漂亮印刷样式。 Comments are retained in the regenerated source properly. 注释将正确保留在重新生成的源中。

In addition, DMS provides source-level pattern matching and transformation (eg, 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.. 此外,DMS提供源级模式匹配和转换(例如,您可以编写“x = x + 1 ==> x ++”,而不是编码所有的walk-around-tree-to-verify,破解树以进行更改。 )参见程序转换的文章 ,了解为什么这样做的工作少得多。

CSharpCodeProvider可能就是你要找的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM