簡體   English   中英

使用 Roslyn API 的自定義診斷規則未在 C# 中應用

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

我已經使用 Roslyn API 在 C# 中實施了自定義診斷規則,但它沒有應用於我的代碼。 我已驗證該規則包含在我項目的代碼分析設置中的已啟用規則列表中,並且該項目已啟用代碼分析。 但是,當我構建項目時,沒有報告應觸發我的自定義規則的代碼的編譯錯誤。

這是我的自定義規則的代碼:

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

這是我希望觸發編譯錯誤的代碼: 因為兩個命名空間定義在一個文件中。

namespace ClassLibrary1
{
    public class Class1
    {


    }
}

namespace ClassLibrary2
{
    public class Class2
    {

    }
}

這是.editorconfig

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

我還將一個示例項目推送到GitHub ,它重現了這個問題。 任何人都可以幫助我理解為什么我的自定義規則沒有被應用以及我該如何解決它? 預先感謝您提供的任何幫助。

指定OutputItemType並將值設置為Analyzer 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM