次の方法で共有


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

更新 : 2007 年 11 月

TypeName

RemoveEmptyFinalizers

CheckId

CA1821

カテゴリ

Microsoft.Performance

互換性に影響する変更点

なし

原因

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

規則の説明

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

違反の修正方法

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

警告を抑制する状況

この規則によるメッセージは抑制しないでください。終了処理を省略した場合のエラーによってパフォーマンスが低下します。また何も利点がありません。

使用例

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

using System.Diagnostics;

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
}