CA1821: 빈 종료자를 제거하십시오.

속성
규칙 ID CA1821
타이틀 빈 종료자를 제거하십시오.
범주 성능
수정 사항이 주요 변경인지 여부 주요 변경 아님
.NET 8에서 기본적으로 사용 제안 사항

원인

형식이 비어 있거나 기본 형식 종료자만 호출하거나 조건부로 내보낸 메서드만 호출하는 종료자를 구현합니다.

규칙 설명

개체 수명을 추적할 때에는 추가로 성능 오버헤드가 발생하므로 가능한 경우 종료자를 사용하지 마세요. 가비지 수집기는 개체를 수집하기 전에 종료자를 실행합니다. 즉, 개체를 수집하려면 둘 이상의 컬렉션이 필요합니다. 빈 종료자는 어떠한 이점도 없이 오버헤드만 가중시킵니다.

위반 문제를 해결하는 방법

빈 종료자를 제거합니다. 디버깅에 종료자가 필요한 경우 전체 종료자를 #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
    }