首页 文章

Roslyn Fix Provider检查修复是否来自预览窗口

提问于
浏览
0

我写了一个修复提供程序,它添加了成员元素resx文件 . 我注意到当visual studio生成预期的更改时,它会调用将资源键添加到文件的方法 .

我正在注册我的FixProvider我正在寻找一种方法来判断是否从预览中调用了该修复程序

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
    var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

    // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
    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<LocalDeclarationStatementSyntax>().First();

    // Register a code action that will invoke the fix.
    context.RegisterCodeFix(
        CodeAction.Create(
            title: title,
            createChangedDocument: c => this.MakeConstAsync(context.Document, declaration, c),
            equivalenceKey: title),
        diagnostic);
}

我如何判断代码修复是否来自一个修复代码而不仅仅是生成预览的操作,我假设有一种方法通过CodeFixContext,如果调用堆栈也不能工作呢?

1 回答

  • 0

    这不安全,没有经过全面测试但是有效 . 因此,您可能会使用自己的风险 . 您可以检查调用堆栈以查看是否从预览窗口调用路径:

    public static bool IsCallFinal()
    {
        var currentStack = new StackTrace();
        return false == currentStack.GetFrames()
                  .Any(x => x.GetMethod().Name == "<GetPreviewOperationsAsync>b__0");
    }
    

相关问题