c# – 用roslyn fix替换注释(在正确的位置添加琐事)
作者:互联网
鉴于以下“代码修复”
我正在尝试替换属性的文档元素,并将其替换为我的快速修复文档.
我正在与琐事作斗争
private Task<Document> AddDocumentationAsync(CodeFixContext context, SyntaxNode root, DocumentationCommentTriviaSyntax xmlElementSyntax)
{
const string comment = "THIS IS THE NEW COMMENT";
var text =
SyntaxFactory.XmlText(SyntaxFactory.TokenList(
SyntaxFactory.XmlTextLiteral(
SyntaxFactory.TriviaList(),
comment,
comment,
SyntaxFactory.TriviaList())));
var textList = SyntaxFactory.List<XmlNodeSyntax>(new[] {text});
XmlNodeSyntax[] nodes = new XmlNodeSyntax[]
{
SyntaxFactory.XmlElement(
SyntaxFactory.XmlElementStartTag(SyntaxFactory.XmlName("summary")),
textList,
SyntaxFactory.XmlElementEndTag(SyntaxFactory.XmlName("summary"))),
};
var list = SyntaxFactory.List<XmlNodeSyntax>(nodes);
var newDocumentation = SyntaxFactory.DocumentationCommentTrivia(
SyntaxKind.SingleLineDocumentationCommentTrivia,
list);
var spaced = newDocumentation.WithTriviaFrom(xmlElementSyntax);
var n1 = root.ReplaceNode(xmlElementSyntax, spaced);
var newDocument = context.Document.WithSyntaxRoot(n1);
return Task.FromResult(newDocument);
}
我获得了这个输出.
如何确保在< summary之前有空格,并且新行字符位于正确的位置,并且公共字符串从新行开始.即
/// <summary>
/// THIS IS THE NEW COMMENT
/// </summary>
public string Test { get; set; }
我的注册码看起来像这样.
var documentationStructure = node.GetDocumentationCommentTriviaSyntax();
var xmlElementSyntax = documentationStructure;
var action = CodeAction.Create("Create XML Documentation", c => this.AddDocumentationAsync(context, root, xmlElementSyntax), "Create XML Documentation");
context.RegisterCodeFix(
action,
diagnostic);
解决方法:
您需要向注释添加EndOfDocumentationCommentToken标记.您可以尝试以下操作:.WithEndOfComment(SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)).
顺便说一句,您可以查看this online tool作为参考.
标签:c,visual-studio-2015,roslyn,roslyn-code-analysis 来源: https://codeday.me/bug/20190628/1314236.html