如何隱藏程式碼分析警告

本文涵蓋建置 .NET 應用程式時,隱藏程式碼分析警告的各種方式。 您可以使用這裡提供的資訊來隱藏程式碼品質規則、程式碼樣式規則和第三方分析器規則。

提示

如果您使用 Visual Studio 作為開發環境,燈泡功能表會提供產生程式碼來隱藏警告的選項。 如需詳細資訊,請參閱隱藏違規

停用規則

您可以在 EditorConfig 或 AnalyzerConfig 組態檔中將其嚴重性設定為 none,以停用造成警告的規則。 此動作會根據您使用的組態檔範圍,停用整個檔案或專案的規則。

[*.{cs,vb}]
dotnet_diagnostic.<rule-ID>.severity = none

如需規則嚴重性的詳細資訊,請參閱設定規則嚴重性

使用前置處理器指示詞

使用 #pragma warning (C#)Disable (Visual Basic) 指示詞,僅隱藏特定程式碼的警告。

    try { ... }
    catch (Exception e)
    {
#pragma warning disable CA2200 // Rethrow to preserve stack details
        throw e;
#pragma warning restore CA2200 // Rethrow to preserve stack details
    }
    Try
        ...
    Catch e As Exception
#Disable Warning CA2200 ' Rethrow to preserve stack details
        Throw e
#Enable Warning CA2200 ' Rethrow to preserve stack details
    End Try

使用 SuppressMessageAttribute

您可以使用 SuppressMessageAttribute 針對專案 (GlobalSuppressions.csGlobalSuppressions.vb) 隱藏來源檔案或全域歸併檔案中的警告。 這個屬性提供一種方式,只隱藏專案或檔案特定部分的警告。

SuppressMessageAttribute 屬性的兩個必要位置參數是規則的 類別以及規則識別碼。 下列程式碼片段會針對這些參數傳遞 "Usage""CA2200:Rethrow to preserve stack details"

[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2200:Rethrow to preserve stack details", Justification = "Not production code.")]
private static void IgnorableCharacters()
{
    try
    {
        ...
    }
    catch (Exception e)
    {
        throw e;
    }
}

如果您將屬性新增至全域歸併檔案,則您會將歸併範圍設定為所需的層級,例如 "member"。 您可以使用 Target 屬性來指定應該隱藏警告的 API。

[assembly: SuppressMessage("Usage", "CA2200:Rethrow to preserve stack details", Justification = "Not production code.", Scope = "member", Target = "~M:MyApp.Program.IgnorableCharacters")]

針對您想要在 Target 屬性中參考的 API,使用文件識別碼。 如需文件識別碼的詳細資訊,請參閱文件識別碼格式

若要隱藏未對應至明確提供使用者來源之編譯器產生程式碼的警告,您必須將歸併屬性放在全域歸併檔案中。 例如,下列程式碼會針對編譯器發出的建構函式隱藏違規:

[module: SuppressMessage("Design", "CA1055:AbstractTypesDoNotHavePublicConstructors", Scope="member", Target="MyTools.Type..ctor()")]

另請參閱