简体   繁体   中英

Roslyn diagnostics registration

I've written up an analyser for VS2015 using the DiagnosticAnalyzer. It is supposed to check whether a class/struct which implements a specific interface also provides a constructor with a specific signature. I'm a bit at a loss about how to register this rule though.

The first two rules apply only to specific methods or constructors and work fine the way they are registered, but how can I minimise the number of times this class-wide rule is invoked while still being called often enough to detect fixes?

public override void Initialize(AnalysisContext context)
{
  // Rule A applies to any method/constructor call.
  context.RegisterSyntaxNodeAction(LiteralInMethodCallViolation,
    SyntaxKind.InvocationExpression);
  context.RegisterSyntaxNodeAction(LiteralInMethodCallViolation,
    SyntaxKind.ObjectCreationExpression);

  // Rule B applies to entire classes/structs.
  context.RegisterSyntaxNodeAction(MissingConstructorViolation, 
    SyntaxKind.????);
}

Edit: using context.RegisterCodeBlockAction(...) seems more appropriate, but the only blocks I get are method and field declarations.

All right, my bad, it's obvious enough. This works:

  context.RegisterSyntaxNodeAction(MissingConstructorViolation, 
                                   SyntaxKind.ClassDeclaration);
  context.RegisterSyntaxNodeAction(MissingConstructorViolation, 
                                   SyntaxKind.StructDeclaration);

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