Roslyn Fix Provider Check if Fix is From Preview Window

放肆的年华 提交于 2019-12-12 05:27:06

问题


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.

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);
}

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?


回答1:


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");
}


来源:https://stackoverflow.com/questions/44206222/roslyn-fix-provider-check-if-fix-is-from-preview-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!