Share via


CA2214:不要呼叫建構函式中的可覆寫方法

屬性
規則識別碼 CA2214
標題 不要呼叫建構函式中的可覆寫方法
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

未密封型別的建構函式會呼叫在其 類別中定義的虛擬方法。

檔案描述

呼叫虛擬方法時,不會選取執行方法的實際類型,直到運行時間為止。 當建構函式呼叫虛擬方法時,叫用方法的實例建構函式可能尚未執行。 如果覆寫的虛擬方法依賴建構函式中的初始化和其他組態,這可能會導致錯誤或非預期的行為。

如何修正違規

若要修正此規則的違規,請勿從類型建構函式內呼叫類型的虛擬方法。

隱藏警告的時機

請勿隱藏此規則的警告。 應該重新設計建構函式,以排除對虛擬方法的呼叫。

範例

下列範例示範違反此規則的效果。 測試應用程式會建立的 DerivedType實例,導致其基類 (BadlyConstructedType) 建構函式執行。 BadlyConstructedType的建構函式不正確地呼叫虛擬方法 DoSomething。 如輸出所示, DerivedType.DoSomething() 會在建構函式執行之前 DerivedType執行。

public class BadlyConstructedType
{
    protected string initialized = "No";

    public BadlyConstructedType()
    {
        Console.WriteLine("Calling base ctor.");
        // Violates rule: DoNotCallOverridableMethodsInConstructors.
        DoSomething();
    }
    // This will be overridden in the derived type.
    public virtual void DoSomething()
    {
        Console.WriteLine("Base DoSomething");
    }
}

public class DerivedType : BadlyConstructedType
{
    public DerivedType()
    {
        Console.WriteLine("Calling derived ctor.");
        initialized = "Yes";
    }
    public override void DoSomething()
    {
        Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized);
    }
}

public class TestBadlyConstructedType
{
    public static void Main2214()
    {
        DerivedType derivedInstance = new DerivedType();
    }
}

Imports System

Namespace ca2214

    Public Class BadlyConstructedType
        Protected initialized As String = "No"


        Public Sub New()
            Console.WriteLine("Calling base ctor.")
            ' Violates rule: DoNotCallOverridableMethodsInConstructors.
            DoSomething()
        End Sub 'New

        ' This will be overridden in the derived type.
        Public Overridable Sub DoSomething()
            Console.WriteLine("Base DoSomething")
        End Sub 'DoSomething
    End Class 'BadlyConstructedType


    Public Class DerivedType
        Inherits BadlyConstructedType

        Public Sub New()
            Console.WriteLine("Calling derived ctor.")
            initialized = "Yes"
        End Sub 'New

        Public Overrides Sub DoSomething()
            Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized)
        End Sub 'DoSomething
    End Class 'DerivedType


    Public Class TestBadlyConstructedType

        Public Shared Sub Main2214()
            Dim derivedInstance As New DerivedType()
        End Sub 'Main
    End Class
End Namespace

這個範例會產生下列輸出:

Calling base ctor.
Derived DoSomething is called - initialized ? No
Calling derived ctor.