【问题标题】:What is required to include in a SuppressMessage attribute?SuppressMessage 属性中需要包含什么?
【发布时间】:2021-12-28 18:34:30
【问题描述】:

我有一些违反了CA1051的代码:

public class Logger {
    // Generates a warning "Do not declare visible instance fields".
    public Level LogLevel = Level.Warning;
}

我想取消这个警告,因为我故意违反了这条规则。 MSDN says 使用 SuppressMessage attribute 这样做:

[SuppressMessage("Design", "CA1051: Do not declare visible instance fields", Justification = "Clearest way of exposing this field.")]
public Level LogLevel = Level.Warning;

all the examples 暗示:

  • 我必须在 MSDN 上找到错误的文档。
  • 我必须查找类别。
  • 我必须查找警告的全名

是否有任何更简单的方法来抑制错误/警告?

【问题讨论】:

  • 我只是好奇打破这条规则的原因是什么。
  • @Silvermind 这只是一个例子,但在这种情况下,我们必须公开一个 getter/setter,它没有提供我们需要的特别好处。所以它为我们节省了 6 行样板代码。
  • @gunr2171 问题重叠,但该问题的措辞方式很难找到 this 问题的答案。那里的核心问题是where are the definitions of IDE messages like IDE1234?,而答案发生是您不需要该消息。我可以通过链接到 docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/… 来回答另一个问题
  • @Silvermind:结构中的公共字段是打破该规则的一个非常可行的理由。

标签: c# .net


【解决方案1】:

是的,有一种更简单的方法可以抑制这样的错误/警告!

// Minimal required:
[SuppressMessage("", "CA1051")]
public Level LogLevel = Level.Warning;

// What I recommend
[SuppressMessage("", "CA1051", Justification = "Clearest way of exposing this field")]
public Level LogLevel = Level.Warning;

它似乎没有记录,但 ID 足以抑制消息。我建议添加Justification,因为这有助于代码的其他读者理解您选择违反规则的原因。

另请注意,Visual Studio 本身将帮助您自动生成这些抑制属性。 VS Code 似乎没有。

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多