C#9 顶级语句文件的属性

Attributes on C#9 top level statements file

我正在尝试将属性添加到顶级语句文件,但我没有找到任何相关信息。可能吗?

对于某些上下文:我只想在该文件中禁用规则:

[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:ElementsMustBeSeparatedByBlankLine", Justification = "Reviewed.")]

这是一条在顶级语句中存在已知错误的规则。

有什么办法吗?

假设你想设置一个程序集范围的属性,那么它和 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

Implicit entry point method

The compiler generates a method to serve as the program entry point for a project with top-level statements. The name of this method isn't actually Main, it's an implementation detail that your code can't reference directly. The signature of the method depends on whether the top-level statements contain the await keyword or the return statement.

...在这种情况下,您需要将代码改回使用传统显式 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)

我有一个与我想使用的 [ExcludeFromCodeCoverage] 属性类似的问题,并收到了适用于 C# 10 的答案。因此,如果您能够迁移到 C# 10,则可以使用 partial class:

执行以下操作

创建一个Program.Attributes.cs(我是这样命名的,所以它嵌套在Program.cs下),代码如下:

[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:ElementsMustBeSeparatedByBlankLine", Justification = "Reviewed.")]
public static partial class Program { }

在此处查看原始答案: