首页 > 其他 > 详细

虚方法重写

时间:2015-06-01 16:32:04      阅读:121      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!