简体   繁体   中英

Custom diagnostic rule not being applied in C# using Roslyn API

I have implemented a custom diagnostic rule in C# using the Roslyn API, but it is not being applied to my code. I have verified that the rule is included in the list of enabled rules in my project's code analysis settings and that code analysis is enabled for the project. However, when I build the project, no compilation errors are reported for code that should trigger my custom rule.

Here is the code for my custom rule:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MoreThanOneNamespaceInFileIsNotAllowedAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "MyRules0001";

    private static readonly LocalizableString Title = "This is a title";
    private static readonly LocalizableString MessageFormat = "This is a message";
    private static readonly LocalizableString Description = "This is a description";
    private const string Category = "Naming";
    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId,
    Title,
    MessageFormat,
    Category,
    DiagnosticSeverity.Error,
    true,
    Description);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();
        context.RegisterSyntaxTreeAction(AnalyzeAction);
    }

    private static void AnalyzeAction(SyntaxTreeAnalysisContext context)
    {
        var syntaxRoot = context.Tree.GetRoot(context.CancellationToken);

        var descentNodes = syntaxRoot.
            DescendantNodes(node => node != null && !node.IsKind(SyntaxKind.ClassDeclaration));

        var foundNode = false;
        foreach (var node in descentNodes)
        {
            if (node.IsKind(SyntaxKind.NamespaceDeclaration))
            {
                if (foundNode)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Rule, Location.None));
                }
                else
                {
                    foundNode = true;
                }
            }
        }
    }
}

And here is the code that I expect to trigger a compilation error: Because two namespaces are defined in a single file.

namespace ClassLibrary1
{
    public class Class1
    {


    }
}

namespace ClassLibrary2
{
    public class Class2
    {

    }
}

And here is the.editorconfig

# My custom StyleCop rule
dotnet_diagnostic.MyRules0001.severity = error

I have also pushed a sample project to GitHub that reproduces the issue. Can anyone help me understand why my custom rule is not being applied and how I can fix it? Thank you in advance for any help you can provide.

Specify OutputItemType with value set to Analyzer . For example:

<ProjectReference Include="..\MyCustomRules\MyCustomRules.csproj">
  <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
  <OutputItemType>Analyzer</OutputItemType>
</ProjectReference>

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