共用方式為


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

型別名稱

DoNotCallOverridableMethodsInConstructors

CheckId

CA2214

分類

Microsoft.Usage

中斷變更

不中斷

原因

非密封型別的建構函式會呼叫類別 (Class) 中所定義的虛擬方法。

規則描述

呼叫虛擬方法後,執行此方法的實際型別會直到執行階段才會選取。當建構函式呼叫虛擬方法時,有可能尚未執行叫用此方法之執行個體的建構函式。

如何修正違規

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

隱藏警告的時機

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

範例

下列範例是違反此規則的影響。測試應用程式會建立 DerivedType 的執行個體,此執行個體會導致執行基底類別 (BadlyConstructedType) 建構函式。BadlyConstructedType 的建構函式會錯誤地呼叫虛擬方法 DoSomething。如輸出所示,DerivedType.DoSomething() 會執行,而且會在執行 DerivedType 的建構函式之前這麼做。

Imports System

Namespace UsageLibrary

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 Main()
        Dim derivedInstance As New DerivedType()
    End Sub 'Main
End Class  
End Namespace
using System;

namespace UsageLibrary
{
    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 Main()
        {
            DerivedType derivedInstance = new DerivedType();
        }
    }
}

這個範例產生下列輸出。