C#:SA1401样式警告无法删除

时间:2016-02-22 05:14:20

标签: c# compiler-warnings stylecop

我试图使用以下代码禁止SA1401(字段名称应该是私有的)警告:

[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Some field names should be capital letters")]
[SuppressMessage("Microsoft.StyleCop.CSharp.Maintainability", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")]
[EventSource(Guid = "9E1C02F1-9B14-4906-AA88-ED2140A102B7")]
public class ProcessApiEventSource : EventSource
{
    /// <summary>
    /// Event source logger instance
    /// </summary>
    public static ProcessApiEventSource Log = new ProcessApiEventSource();
    ...
}

SA1306警告被抑制时,SA1401警告未被抑制。任何人都可以建议抑制为什么不起作用?此外,有没有办法使用访问器更改声明,以便代码遵守该规则,并清除该警告本身?

2 个答案:

答案 0 :(得分:3)

[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")]

我用它来抑制消息,如here所述。

答案 1 :(得分:1)

要使错误消失,您可以将公共字段转换为私有字段,并将其公开为公共属性。

public class ProcessApiEventSource : EventSource
{
    private static ProcessApiEventSource MyLog = new ProcessApiEventSource();

    public static ProcessApiEventSource Log  { get { return MyLog; } }
}

如果您使用的是.NET 4.6,那么您也可以使用仅限getter的属性表达式。

public class ProcessApiEventSource : EventSource
{
    public static ProcessApiEventSource Log => new ProcessApiEventSource();
}