现在的位置: 首页 > 综合 > 正文

关于虚方法(Virtual)的理解

2012年10月14日 ⁄ 综合 ⁄ 共 845字 ⁄ 字号 评论关闭

         可以运行一下试试~你就会明白

using System;
using System.Collections.Generic;
using System.Text;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            FlowB flowB = new FlowB();
            flowB.Run(); //复用了Flow的流程并采用了自己的B步骤
            Console.ReadLine();
        }
    }
    public class Flow
    {
        public void A()
        {
            Console.WriteLine("F A");
        }

        public virtual void B()
        {
            Console.WriteLine("F B");
        }

        public void C()
        {
            Console.WriteLine("F C");
        }

        public void Run()
        {
            A();
            B(); //步骤B是扩展点 ,可以由子类决定具体执行什么
            C();
        }
    }

    public class FlowA : Flow
    {
        public override void B()
        {
            //执行FlowA的B步骤
        }
    }

    public class FlowB : Flow
    {
        public override void B()
        {
            Console.WriteLine("FBB");
        }
    }

}

抱歉!评论已关闭.