简体   繁体   中英

Roslyn - CodeFixProvider is being fired but DiagnosticAnalyzer not for class destructor

Pseudo-code for my analyser

My test class:

public class TestClass
{
     ~TestClass()
     {
     }
}

My diagnostic analyzer class with analyze method:

public class TestClassAnalyzer : DiagnosticAnalyzer
{
     public const string AnalyzerId = "TestId";

     ...

     private static void AnalyzeSymbol(SymbolAnalysisContext context)
     {
           var methodDeclaration = (IMethodSymbol)context.Symbol;

           if (methodDeclaration.MethodKind == MethodKind.Destructor)
           {
               return;
           }

           context.ReportDiagnostic(Diagnostic.Create(...));
     }
}

My code fix provider with fix method:

public class TestClassCodeFixProvider : CodeFixProvider
{
     public sealed override ImmutableArray<string> FixableDiagnosticIds =>
          ImmutableArray.Create(TestClassAnalyzer.AnalyzerId);


     ...

     private async Task<Solution> PerformFixAsync(Document document, ...)
     {
          ...

          return await Renamer.RenameSymbolAsync(...)
     }
}

If I put a breakpoint after the line with check for destructor inside my TestClassAnalyzer class, then my code never stops/breaks which makes sense to me because I jump out of the method with return keyword. Nevertheless, my code fix is being fired (I can put breakpoint inside the PerformFixAnync method and code stops/breaks there) and I can see red squiggly.

CodeFixProvider

Does anybody have any idea why the code fix is being fired although it shouldn't?

I guess your analyzer returns early for descructors as the condition is wrong:

if (methodDeclaration.MethodKind == MethodKind.Destructor)
{
    return;
}

context.ReportDiagnostic(Diagnostic.Create(...));

negate the condition or report the condition in the then-block:

if (methodDeclaration.MethodKind != MethodKind.Destructor)
{
    return;
}

context.ReportDiagnostic(Diagnostic.Create(...));

It turned out that my solution contained another class buried somewhere between folders with some old code without destructor check condition and this was causing the troubles. This class was not event part of the source code in TFS ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM