【问题标题】:Attributes on C#9 top level statements fileC#9 顶级语句文件上的属性
【发布时间】:2021-12-25 23:37:38
【问题描述】:

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

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

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

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

有什么办法吗?

【问题讨论】:

  • ...还是要将属性添加到由顶级作用域表示的匿名方法中?
  • 我只想将它添加到程序类/文件中。我不确定顶级语句是如何在幕后工作的,但我想会生成一个 Program 类

标签: c# c#-9.0


【解决方案1】:

假设您要设置程序集范围的属性,那么它与 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)

【讨论】:

  • 这不会影响所有项目文件吗?我希望它只影响“程序”类/文件
  • @Iván 我已经扩展了我的答案。
  • 好的,那我得等到 StyleCop 修复顶级语句交互。谢谢!
  • @Iván 你有什么理由不能使用.editorconfig#pragma 代替吗? SuppressMessage 属性早已过时。多年来我不需要使用它...
  • @Iván 我认为您使用的是 legacy StyleCop,因为 Roslyn 集成 StyleCop 使用 #pragma: github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2278 - 例如 SA1516:ElementsMustBeSeparatedByBlankLine 规则使用#pragma warning disable SA1516(见github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/…
猜你喜欢
  • 2023-01-27
  • 2023-01-26
  • 2021-03-17
  • 2022-01-23
  • 1970-01-01
  • 2012-01-14
  • 2022-11-13
  • 1970-01-01
  • 2012-11-21
相关资源
最近更新 更多