發表文章

目前顯示的是 7月, 2010的文章

不要在建構子中呼叫虛擬函式

圖片
最近發現當在建構子中設計要去呼叫虛擬函式時,會發生衍生類別因為還未完全執行完建構子的初始化動作,就直接呼叫它所改寫的虛擬函式的話,可能會引發一些問題。 例如: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VS2020Test { public class CallVirtualFuncFromCtor { public static void UT() { MyDerivative md = new MyDerivative(2, 5); } } public class MyBase { protected int id = 0; public MyBase( int i) { id = i; ShowID(); } public virtual void ShowID() { Console.WriteLine( "[Base] ID " + id.ToString()); } } public class MyDerivative : MyBase { protected int id2 = 0; public MyDerivative( int id, int id2) : base (id) { this .id2 = id2; } public override void ShowID() { Console.WriteLine( "[Derivative] ID " + id.ToString() +