是否可以选择在不创建 "GlobalSuppressions.cs" 文件的情况下停用样式警察规则?

Is there an option to deactivate style cop rule without making an "GlobalSuppressions.cs" file?

我们在项目中使用 StyleCop Analyzer。我的任务之一是停用一些规则,但不创建 GlobalSuppressions.cs 文件。

我找到了解决方案,但仅限于创建此文件,所以我很困惑。

要在 GlobalSuppressions.cs 之外抑制警告,您可以:

使用注释(记得恢复范围外的警告!)

#pragma warning disable IDE0052 // Remove unread private members
private readonly Object _obj;
#pragma warning restore IDE0052 // Remove unread private members

或使用 SuppressMessage 属性

[SuppressMessage("Code Quality", "IDE0052:Remove unread private members", Justification = "<Pending>")]
private readonly Object _obj;

如果你想全局禁用它们,你也可以配置一个规则集文件。

在你的 csproj 中:

<PropertyGroup>
    <CodeAnalysisRuleSet>File.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>

然后根据需要创建 File.ruleset。大概长得像

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
  <Rules AnalyzerId="Microsoft.CodeQuality.Analyzers" RuleNamespace="Microsoft.CodeQuality.Analyzers">
    <Rule Id="CA1056" Action="None" />
  </Rules>
  </Rules>
</RuleSet>

更多详情请见 https://docs.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2019#rule-sets