【发布时间】:2019-11-28 10:36:00
【问题描述】:
我已识别出一个节点,该节点的字符串中包含我的分析器正确识别的值。然后我创建了一个可以成功检索字符串的 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
}
【问题讨论】:
标签: c# roslyn roslyn-code-analysis