标签:
控制台程序
class Program { static void Main(string[] args) { DerivedType derivedInstance = new DerivedType(); string line; while ((line = Console.ReadLine()) != null) { Console.WriteLine("----"); } } } 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); } }
结果
分析:
实例化DerivedType时候,调用BadlyConstructedType时,执行的DoSomething是DerivedType重写的方法,而非父类。
所以在使用的虚方法重写时,需要特别注意。
标签:
原文地址:http://www.cnblogs.com/xcsn/p/4544041.html