共用方式為


如何隱藏程式代碼分析警告

本文涵蓋建置 .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;
    }
}

如果您將屬性新增至全域抑制檔案,請將抑制範圍設為所需的層級,例如 。 您可以使用 Target 屬性指定應該在該 API 上抑制的警告。

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

屬性中,使用您想要參考的 API 的Target。 如需文件識別碼的相關信息,請參閱 文件標識碼格式。

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

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

另請參閱