码迷,mamicode.com
首页 > 其他好文 > 详细

虚方法重写

时间:2015-06-01 16:35:17      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

控制台程序

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时,执行的DoSomethingDerivedType重写的方法,而非父类。

所以在使用的虚方法重写时,需要特别注意。

 

虚方法重写

标签:

原文地址:http://www.cnblogs.com/xcsn/p/4544041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!