我已经确定了一个节点,该节点的字符串中有一个值,我的分析器可以正确识别该值。然后,我创建了一个CodeFixProvider,它可以成功检索字符串,然后我想替换字符串的特定部分。我现在想替换文档中的字符串以修复警告。我如何最好地应用此修复程序?
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LiteralExpressionSyntax>().First();
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: regex,
createChangedSolution: c => ReplaceRegexAsync(context.Document, declaration, c),
equivalenceKey: regex),
diagnostic);
}
private async Task<Solution> ReplaceRegexAsync(Document document, LiteralExpressionSyntax typeDecl, CancellationToken cancellationToken)
{
var identifierToken = typeDecl.Token;
var updatedText = identifierToken.Text.Replace("myword", "anotherword");
// Todo how to replace original text to apply fix
}
CodeAction.Create
签名与createChangedSolution
一起使用,而不是createChangedDocument
可能更好。它允许在解决方案中注册修补单个文档的修复程序。SyntaxTree
或SourceText
将更改应用到文档上>...
context.RegisterCodeFix(
CodeAction.Create(
title: regex,
createChangedDocument:c => ReplaceRegexAsync(context.Document, declaration, c),
equivalenceKey: regex),
diagnostic);
private async Task<Document> ReplaceRegexAsync(Document document, LiteralExpressionSyntax typeDecl, CancellationToken cancellationToken)
{
var identifierToken = typeDecl.Token;
var updatedText = identifierToken.Text.Replace("myword", "anotherword");
var valueText = identifierToken.ValueText.Replace("myword", "anotherword");
var newToken = SyntaxFactory.Literal(identifierToken.LeadingTrivia, updatedText, valueText, identifierToken.TrailingTrivia);
var sourceText = await typeDecl.SyntaxTree.GetTextAsync(cancellationToken);
// update document by changing the source text
return document.WithText(sourceText.WithChanges(new TextChange(identifierToken.FullSpan, newToken.ToFullString())));
}