不要在構造函數中調用可重寫的方法


非密封類型的構造函數調用其類中定義的虛方法。

調用虛方法時,直到運行時之前都不會選擇執行該方法的實際類型。構造函數調用虛方法時,可能尚未執行調用該方法的實例的構造函數。

要修復與該規則的沖突,請不要從某類型的構造函數中調用該類型的虛方法。

不要禁止顯示此規則發出的警告。應重新設計該構造函數,以取消對虛方法的調用。

下面的示例演示與該規則沖突產生的影響。測試應用程序創建 DerivedType 的實例,使其基類 (BadlyConstructedType) 構造函數開始執行。BadlyConstructedType 的構造函數錯誤地調用虛方法 DoSomething。如輸出所示,DerivedType.DoSomething() 將執行,並且是在DerivedType 的構造函數執行前開始執行。

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();
        }
    }
}

該示例產生下面的輸出。

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

參考:https://msdn.microsoft.com/zh-cn/library/ms182331(VS.90).aspx


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM