首页> 外文期刊>MSDN Magazine >Language-Agnostic Code Generation with Roslyn
【24h】

Language-Agnostic Code Generation with Roslyn

机译:Roslyn的语言不可知代码生成

获取原文
获取原文并翻译 | 示例
       

摘要

The Roslyn code base provides powerful APIs you can leverage to perform rich code analysis over your source code. For instance, analyzers and code refactorings can walk through a piece of source code and replace one or more syntax nodes with new code you generate with the Roslyn APIs. A common way to perform code generation is via the SyntaxFactory class, which exposes factory methods to generate syntax nodes in a way that compilers can understand. The SyntaxFactory class is certainly very powerful because it allows generating any possible syntax element, but there are two different SyntaxFactory implementations: MicrosoftCodeAnalysis.CSharp.SyntaxFactoryandMicrosoft.Code-Analysis.VisualBasic.SyntaxFactory. This has an important implication if you want to write an analyzer with a code fix that targets both C# and Visual Basic-you have to write two different analyzers, one for C# and one for Visual Basic, using the two implementations of SyntaxFactory, each with a different approach due to the different way those languages handle some constructs. This likely means wasting time writing the analyzer twice, and maintaining them becomes more difficult. Fortunately, the Roslyn APIs also provide the MicrosoftCodeAnalysis.Editing.SyntaxGenerator, which allows for language-agnostic code generation. In other words, with Syntax-Generator you can write your code-generation logic once and target both C# and Visual Basic. In this article I'll show you how to perform language-agnostic code generation with SyntaxGenerator, and I'll give you some hints about the Roslyn Workspaces APIs.
机译:Roslyn代码库提供了强大的API,您可以利用它们对源代码执行丰富的代码分析。例如,分析器和代码重构可以遍历一段源代码,并用您使用Roslyn API生成的新代码替换一个或多个语法节点。执行代码生成的一种常用方法是通过SyntaxFactory类,该类公开了工厂方法以编译器可以理解的方式生成语法节点。 SyntaxFactory类肯定非常强大,因为它允许生成任何可能的语法元素,但是有两种不同的SyntaxFactory实现:MicrosoftCodeAnalysis.CSharp.SyntaxFactory和Microsoft.Code-Analysis.VisualBasic.SyntaxFactory。如果要编写一个同时针对C#和Visual Basic的代码修复程序的分析器,则这具有重要意义-必须使用SyntaxFactory的两个实现编写两个不同的分析器,一个用于C#,一个用于Visual Basic。由于这些语言处理某些构造的方式不同,因此采用了不同的方法。这可能意味着浪费时间两次编写分析器,并且维护它们变得更加困难。幸运的是,Roslyn API还提供了MicrosoftCodeAnalysis.Editing.SyntaxGenerator,它允许生成与语言无关的代码。换句话说,使用Syntax-Generator可以编写一次代码生成逻辑,并同时针对C#和Visual Basic。在本文中,我将向您展示如何使用SyntaxGenerator执行与语言无关的代码生成,并向您提供有关Roslyn Workspaces API的一些提示。

著录项

  • 来源
    《MSDN Magazine》 |2016年第6期|22-2426-28|共6页
  • 作者

    Alessandro Del Sole;

  • 作者单位
  • 收录信息
  • 原文格式 PDF
  • 正文语种 eng
  • 中图分类
  • 关键词

  • 入库时间 2022-08-18 02:49:10

相似文献

  • 外文文献
  • 中文文献
  • 专利
获取原文

客服邮箱:kefu@zhangqiaokeyan.com

京公网安备:11010802029741号 ICP备案号:京ICP备15016152号-6 六维联合信息科技 (北京) 有限公司©版权所有
  • 客服微信

  • 服务号