C#虚方法的重写

为什么80%的码农都做不了架构师?>>>   hot3.png

情景:子类调用父类构造函数,父类构造函数调用虚函数,子类重写该虚方法。
结果:执行的是子类覆写的方法

输出结果: sonClass: son

using System;

namespace VirtualOverrideTest
{
    public class FatherClass
    {
        public string Name
        {
            get { return Name; }
            set { Name = value; }
        }
        public FatherClass(string name)
        {
            this.WriteName(name);
        }
        public virtual void WriteName(string name)
        {
            this.Name = name + "Father";
        }
    }
    public class SonClass: FatherClass
    {
        public string Name = null;
       
        public SonClass(string name): base(name)
        {
        }
        public override void WriteName(string name)
        {
             this.Name += name + "son";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SonClass son = new SonClass("sonClass: ");
            Console.WriteLine(son.Name);
        }
    }
}

 

 

转载于:https://my.oschina.net/mj23/blog/681343

你可能感兴趣的:(C#虚方法的重写)