CA1821:必須移除空的完成項

屬性
規則識別碼 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
    }