CA1821: Usuń puste finalizatory

Właściwości Wartość
Identyfikator reguły CA1821
Tytuł Usuwaj puste finalizatory
Kategoria Wydajność
Poprawka powodująca niezgodność lub niezgodność Niezgodność
Domyślnie włączone na platformie .NET 8 Jako sugestia

Przyczyna

Typ implementuje finalizator, który jest pusty, wywołuje tylko finalizator typu podstawowego lub wywołuje tylko warunkowo emitowane metody.

Opis reguły

Zawsze, gdy to możliwe, unikaj finalizatorów ze względu na dodatkowe obciążenie wydajności związane z śledzeniem okresu istnienia obiektu. Moduł odśmieceń pamięci uruchamia finalizator, zanim zbierze obiekt. Oznacza to, że do zbierania obiektu wymagane są co najmniej dwie kolekcje. Pusty finalizator powoduje naliczenie tego dodatkowego obciążenia bez żadnych korzyści.

Jak naprawić naruszenia

Usuń pusty finalizator. Jeśli do debugowania jest wymagany finalizator, należy ująć cały finalizator w #if DEBUG / #endif dyrektywy.

Kiedy pomijać ostrzeżenia

Nie pomijaj komunikatu z tej reguły.

Przykład

W poniższym przykładzie pokazano pusty finalizator, który należy usunąć, finalizator, który powinien być ujęty w #if DEBUG / #endif dyrektywy, oraz finalizator, który prawidłowo używa #if DEBUG / #endif dyrektyw.

    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
    }