上下文:
我工作的环境有很多“魔术”方法和字段,这些方法和字段是通过外部代码的反射来调用或设置的。某些内容可能具有属性,这意味着它将被设置为非默认值,但是Visual Studio仍然看不到该方面,并且“有帮助”地提供了警告。
由于这些都是使用属性和专门命名的方法来处理的,因此理想情况下,我想向VS提供其他信息,以便它知道它是被调用还是已设置,而无需我手动抑制每个警告。
我已经考虑编写Roslyn分析器,但是据我所知,我只能添加其他警告,而不能修改现有警告/引用计数。
示例:
[MyCmpGet] private Component comp
“字段从未分配给它,并且其默认值始终为null”
但是由于注释,通过反射分配了该字段。
[HarmonyPatch]
class Patch
{
static void Postfix() {}
}
“未使用私人成员”“ 0个参考”
但是由于类上有注释,并且该方法具有特定的名称,因此通过反射调用该方法。
问题:
让Visual Studio知道正在设置这些字段并且正在引用这些方法的最佳方法是什么?最好不要要求我对每个操作都采取手动操作,也不要在示例代码中添加任何其他内容。
您可以实现DiagnosticSuppressor
分析器。默认的分析器模板应生成一个nuget程序包,您可以将该程序包包含在要禁止此警告的所有项目中。
这里是诊断抑制器最基本形式的示例:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class DiagnosticSuppressorForAssignmentWarnings : DiagnosticSuppressor {
public SuppressionDescriptor SuppressionDescriptor => new SuppressionDescriptor(
id: "SPR0001", // Id for this analyzer suppressor (You should come up with a unique name for yours)
suppressedDiagnosticId: "CS0649", // The warning that we may want to suppress
justification: "This is ok because it is assigned via reflection");
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
// You can pass in multiple suppression descriptors to have this suppress multiple types of warnings
=> ImmutableArray.Create(SuppressionDescriptor);
public override void ReportSuppressions(SuppressionAnalysisContext context) {
foreach (var diagnostic in context.ReportedDiagnostics) {
// The parsed syntax tree of the file that this warning comes from
var syntaxTree = diagnostic.Location.SourceTree;
// The syntax Node that the warning was reported for
var nodeWithWarning = syntaxTree.GetRoot().FindNode(diagnostic.Location.SourceSpan);
// A semantic model that can answer questions like 'does this attribute inherit from this type' etc.
var semanticModel = context.GetSemanticModel(syntaxTree);
// You can do additional analysis of the source to ensure this is something
// that is semantically safe to suppress (like check for an attribute)
context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic));
}
}
}