使用Roslyn生成格式正确的语法 [英] Generating well-formatted syntax with Roslyn

查看:74
本文介绍了使用Roslyn生成格式正确的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Roslyn修改C#文件的语法。使用CSharpSyntaxRewriter,可以很容易地在语法树中查找和替换节点。但是,生成的代码非常丑陋,甚至在所有情况下都无法解析,因为我创建的语法节点(使用SyntaxFactory)甚至缺少最少的空白琐事。 Roslyn是否提供一些基本的格式化功能来避免这种情况,或者我必须手动将琐事添加到我创建的每个节点上?

I am using Roslyn to modify the syntax of C# files. Using CSharpSyntaxRewriter, it is very easy to find and replace nodes in the syntax tree. However, the generated code is very ugly and won't even parse in all cases because the syntax nodes I create (using SyntaxFactory) lack even a minimal amount of whitespace trivia. Does Roslyn provide some basic formatting functionality to avoid this or do I have to add trivia manually to each node I create?

推荐答案

是-使用 Microsoft.CodeAnalysis.Formatting.Formatter

var formattedResult = Formatter.Format(syntaxNode, workspace);

这篇关于使用Roslyn生成格式正确的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆