假设您要设置程序集范围的属性,那么它与 C# 9.0 之前的相同。您缺少 assembly: 关键字。
https://docs.microsoft.com/en-us/dotnet/standard/assembly/set-attributes
更改您的代码以添加 assembly: 关键字,如下所示:
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:ElementsMustBeSeparatedByBlankLine", Justification = "Reviewed.")
如果你想将属性添加到隐式入口点方法(又名Program.Main)或其父类型class Program,那么你不能,因为 C# 9.0 的顶级语句设计根本不允许程序命名或引用该方法。
在顶级方法的文档中简要提到了这一点(强调我的):
https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements#implicit-entry-point-method
隐式入口点方法
编译器生成一个方法,作为具有顶级语句的项目的程序入口点。这个方法的名字实际上不是 Main,它是一个实现细节你的代码不能直接引用。方法的签名取决于顶层语句是否包含await关键字或return 声明。
...在这种情况下,您需要将代码改回使用传统的显式Main 方法:
[SuppressMessage("SomeClassRule", "", Justification = "It's my computer")]
public static class Program
{
[SuppressMessage("SomeMethodRule", "", Justification = "It's my computer")]
public static async Task<Int32> Main( String[] args )
{
return 0;
}
}
但是...,由于您想在 Main 方法上使用 [SuppressMessage] 来抑制 StyleCop 警告,您需要意识到 StyleCop(如与 .NET 中的其他静态分析工具一起使用)现在尊重 .editorconfig 和 #pragma warning disable|restore 来禁止或禁用警告和检查。
以下是#pragma 与[SuppressMessage] 的快速比较:当一项技术具有“更好”的特性时,它会以粗体标记:
|
#pragma warning disable |
[SuppressMessage] |
| Compiled into output assembly, growing your DLL size from all the constant strings and potentially exposing internal development details to external users |
No |
Yes |
Explicit Justification field |
No
But you can add an explanatory comment on the same line. |
Yes |
| Explicit target field for disambiguation |
No |
Yes |
| Requires modern versions of Visual Studio (2017 or 2019+) |
Yes |
No |
| Granularity |
Source code line
But if the same warning appears 2 or more times on the same source code line you cannot disambiguate |
Discrete .NET assembly objects (types, parameters, fields, etc - but not per-line) |