你所看到RS2000
的有点不同。这是从诊断分析器报告的诊断规则。它使用相同的DiagnosticDescriptor
类,但对源生成器的处理方式不同。例如,DiagnosticAnalyzer
期望派生类提供支持的诊断列表(通过SupportedDiagnostics
)。
诊断报告DiagnosticAnalyzer
这是一个诊断分析器的极简示例:
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MyDiagnosticAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
id: "MYCUSTOMID001",
title: "Unexpected Error",
messageFormat: "Error for object",
category: "Design",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "MYCUSTOMID001 long description. This line will be shown in the error list panel");
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)
{
// ...
context.ReportDiagnostic(Diagnostic.Create(Rule, Location.None));
}
}
它报告一个警告,其中包含从实例的Description
getter 中使用的可扩展详细信息:DiagnosticDescriptor
诊断报告SourceGenerator
虽然它适用于诊断分析器,但它似乎不适用于源生成器。
[Generator]
public sealed class MySourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
// ...
var descriptor = new DiagnosticDescriptor(
id: "MYCUSTOMID002",
title: "Unexpected Error",
messageFormat: "Error for object",
category: "Design",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "MYCUSTOMID002 long description. This line will be shown in the error list panel");
context.ReportDiagnostic(Diagnostic.Create(descriptor, Location.None));
}
}
如我们所见,Description
消息中没有显示:
解决方法(嗯,不是真的)
您仍然可以使用该MessageFormat
属性从源生成器提供有意义的诊断详细信息,并将正确的格式参数传递给Diagnostic.Create
以后。
这是一个例子:
public void Execute(GeneratorExecutionContext context)
{
// ...
var descriptor = new DiagnosticDescriptor(
id: "MYCUSTOMID002",
title: "Unexpected Error",
messageFormat: "Error for object: {0}",
category: "Design",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
context.ReportDiagnostic(Diagnostic.Create(descriptor, Location.None, "Exception long description, stack trace, etc."));
}
它将产生以下消息:
但我知道这不是您正在寻找的。