【问题标题】:How to configure StyleCop to suppress warnings on generated code?如何配置 StyleCop 以抑制生成代码的警告?
【发布时间】:2023-12-02 14:23:02
【问题描述】:

另一个项目,Visual Studio 的代码分析有这个选项。但我在 StyleCop(AKA 源分析)中找不到它。

我要忽略的文件是 dbml 的 .designer.cs 代码,其中包含 // <autogenerated> 标记。 A blog post 告诉我这就足够了,但在我的情况下它不是。

【问题讨论】:

    标签: .net visual-studio code-generation code-analysis stylecop


    【解决方案1】:

    StyleCop: How To Ignore Generated Code

    编辑:这是我在生成的 ANTLR 语法中使用的标头。这实际上是 StringTemplate 模板的主体,因此两个 \> 条目实际上只是转义了 > 标记。除了<auto-generated> 标签和[GeneratedCode] 属性,我们还需要禁用一些在代码分析过程中出现的警告。

    //------------------------------------------------------------------------------
    // \<auto-generated>
    //     This code was generated by a tool.
    //     ANTLR Version: ANTLRVersion
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // \</auto-generated>
    //------------------------------------------------------------------------------
    
    // $ANTLR <ANTLRVersion> <fileName>
    
    // The variable 'variable' is assigned but its value is never used.
    #pragma warning disable 219
    // Unreachable code detected.
    #pragma warning disable 162
    // Missing XML comment for publicly visible type or member 'Type_or_Member'
    #pragma warning disable 1591
    // CLS compliance checking will not be performed on 'type' because it is not visible from outside this assembly.
    #pragma warning disable 3019
    // 'type' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute.
    #pragma warning disable 3021
    
    [System.CodeDom.Compiler.GeneratedCode("ANTLR", "<ANTLRVersion>")]
    [System.CLSCompliant(false)]
    public class ...
    

    【讨论】:

    • 当前版本不支持。我不是唯一一个抱怨它的人,他们的错误跟踪器中还有更多人。
    • -1:这不是问题:Jader 没有询问是否有其他选项可以忽略自动生成的代码,而是询问为什么它不能以// &lt;autogenerated&gt; 方式工作。我认为每个可以 google 的人都会首先访问您的链接页面,但如果它不起作用,它也无济于事。它对我也不起作用,即使我的文件确实是自动生成的并且标题已由该软件设置。
    • 我用代码示例更新了帖子。我注意到这个问题指的是&lt;autogenerated&gt;,我的代码实际上是在使用&lt;auto-generated&gt;。也许这就是问题所在?