Roslyn Fix Provider 检查修复是否来自预览窗口 [英] Roslyn Fix Provider Check if Fix is From Preview Window

查看:42
本文介绍了Roslyn Fix Provider 检查修复是否来自预览窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written a fix provider which adds members elements resx file. I noticed when visual studio generates the expected changes it calls the method in which add the resource keys to the file.

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

I'm registering my FixProvider I'm looking for a way to tell if the fix was called from a preview

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,如果不是调用堆栈也可以工作?

How can I tell if the code fix is coming from an action which is mean to fix code and not just generate a preview, I'm assuming there is a way through the CodeFixContext if not the call stack could work too?

推荐答案

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

This is not safe, not fully tested but it works. So you may use at you're own risk. You can check up the call stack to see if the path is being called from the preview window:

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

这篇关于Roslyn Fix Provider 检查修复是否来自预览窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆