How to add white space and/or format code?

拈花ヽ惹草 提交于 2019-12-18 04:39:08

问题


Given that I have created a symbol using SymbolFactory.CreateProperty, how would I add white space. Currently I get accessibility, modifiers, name, type etc. all stringed together when writing out document. Maybe I am writing it out wrong, or I need to add extra step to add white space? I use document.GetText() to write it out to console.


回答1:


Nope, that's what you expect. Generated nodes don't have whitespace, with the intent you'll process it once you're done.

There are two options:

  1. Call .NormalizeWhitespace() on the nodes. This is an aggressive formatter that is really only useful if you're generating code you don't intend to be consumed by a human -- it makes the output "valid" but blows away any existing formatting.
  2. Call Formatter.Format(), from Microsoft.CodeAnalysis.Formatting. This is the fancy formatter which will attempt to preserve existing whitespace and such, and will only update the nodes that need fixing. This is best if you're updating user code and you don't want to stomp on it.



回答2:


I had the same issue, and I found this to work the best:

node.WithTrailingTrivia(SyntaxFactory.Space)

where node is a SyntaxToken of any kind.



来源:https://stackoverflow.com/questions/19711218/how-to-add-white-space-and-or-format-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!