ReportDiagnostic 部分 类

ReportDiagnostic on Partial Classes

我正在修改来自代码分析器模板的默认分析器项目,以尝试让它报告部分 class 的所有声明。

我已将代码修改为:

public override void Initialize(AnalysisContext context)
{
    context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
}

private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
    var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

    // Find just those named type symbols with names containing lowercase letters.
    if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower))
    {
        foreach (var location in namedTypeSymbol.Locations)
        {
            // For all such symbols, produce a diagnostic.
            var diagnostic = Diagnostic.Create(Rule, location, namedTypeSymbol.Name);
            context.ReportDiagnostic(diagnostic);
        }
    }
}

在两个单独的文件中,我有部分 class 是这样的:

// File1.cs
partial class Foo
{
    public string BarString;
}

// File2.cs
partial class Foo
{
    public string FooBarString;
}

我在 ReportDiagnostic 上设置了断点,我看到它在每个位置都被调用,但在 Visual Studio 内它只报告单个文件中的诊断信息。

如果我将 Foo 的多个实现放在一个文件中(它恰好报告了该文件声明),那么我将看到两个诊断报告。

我是不是误解了应该如何报告诊断信息,或者这是一个错误?如果是bug,是Roslyn的问题还是Visual Studio消费Roslyn的问题?

这是 Visual Studio 诊断服务的 V1 实施的限制。

Roslyn 存储库中有一个问题可以跟踪此问题:

https://github.com/dotnet/roslyn/issues/3748#issuecomment-117231706

来自 Github 问题的回复:

This is a known issue in the v1 implementation of the Visual Studio IDE's diagnostic service. It currently doesn't handle analyzer reporting diagnostics outside the document being analyzed. So, if File1.cs has the primary definition of Foo for which AnalyzeSymbol was invoked, then the diagnostic service only retains diagnostics reported by the analyzer within this file.