CA1821:空のファイナライザーを削除します

プロパティ
ルール ID CA1821
Title 空のファイナライザーを削除します
[カテゴリ] パフォーマンス
修正が中断ありか中断なしか なし
.NET 8 では既定で有効 提案として

原因

型が空のファイナライザーを実装しているか、基本データ型のファイナライザーだけを呼び出しているか、条件付きで出力されたメソッドのみを呼び出しています。

規則の説明

オブジェクトの有効期間の追跡に関連するパフォーマンス オーバーヘッドが増大するため、ファイナライザーは可能な限り使用しないでください。 ガベージ コレクターは、オブジェクトを収集する前にファイナライザーを実行します。 これは、オブジェクトを収集するために少なくとも 2 つのコレクションが必要であることを意味します。 空のファイナライザーを使用すると、オーバーヘッドが増大するだけで何の利点もありません。

違反の修正方法

空のファイナライザーを削除します。 デバッグにファイナライザーが必要な場合は、ファイナライザー全体を #if DEBUG / #endif ディレクティブで囲みます。

どのようなときに警告を抑制するか

この規則によるメッセージは抑制しないでください。

次の例は、削除する必要がある空のファイナライザー、#if DEBUG / #endif ディレクティブで囲む必要があるファイナライザー、および #if DEBUG / #endif ディレクティブを正しく使用しているファイナライザーを示しています。

    public class Class1
    {
        // Violation occurs because the finalizer is empty.
        ~Class1()
        {
        }
    }

    public class Class2
    {
        // Violation occurs because Debug.Fail is a conditional method.
        // The finalizer will contain code only if the DEBUG directive
        // symbol is present at compile time. When the DEBUG
        // directive is not present, the finalizer will still exist, but
        // it will be empty.
        ~Class2()
        {
            Debug.Fail("Finalizer called!");
        }
    }

    public class Class3
    {
#if DEBUG
        // Violation will not occur because the finalizer will exist and
        // contain code when the DEBUG directive is present. When the
        // DEBUG directive is not present, the finalizer will not exist,
        // and therefore not be empty.
        ~Class3()
        {
            Debug.Fail("Finalizer called!");
        }
#endif
    }