CA2216:可處置的類型應該宣告完成項

屬性
規則識別碼 CA2216
標題 可處置的類型應該宣告完成項
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

實作 System.IDisposable的型別,且具有建議使用 Unmanaged 資源的欄位,不會實作完成項,如 所述 System.Object.Finalize

檔案描述

如果可處置類型包含下列類型的欄位,則會報告違反此規則:

如何修正違規

若要修正此規則的違規,請實作呼叫方法 Dispose 的完成項。

隱藏警告的時機

如果類型未 IDisposable 實作,以釋放 Unmanaged 資源的目的,則隱藏此規則的警告是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA2216
// The code that's violating the rule is on this line.
#pragma warning restore CA2216

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

[*.{cs,vb}]
dotnet_diagnostic.CA2216.severity = none

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

範例

下列範例顯示違反此規則的類型。

public class DisposeMissingFinalize : IDisposable
{
    private bool disposed = false;
    private IntPtr unmanagedResource;

    [DllImport("native.dll")]
    private static extern IntPtr AllocateUnmanagedResource();

    [DllImport("native.dll")]
    private static extern void FreeUnmanagedResource(IntPtr p);

    DisposeMissingFinalize()
    {
        unmanagedResource = AllocateUnmanagedResource();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            // Dispose of resources held by this instance.
            FreeUnmanagedResource(unmanagedResource);
            disposed = true;

            // Suppress finalization of this disposed instance.
            if (disposing)
            {
                GC.SuppressFinalize(this);
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }

    // Disposable types with unmanaged resources implement a finalizer.
    // Uncomment the following code to satisfy rule:
    //  DisposableTypesShouldDeclareFinalizer
    // ~TypeA()
    // {
    //     Dispose(false);
    // }
}

CA1816:正確呼叫 GC.SuppressFinalize

另請參閱