C#委托本质探索 七、方法变量作为函数参数传递

// 将方法变量作为函数参数传递,又叫回调
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1.SeventhTest
{
    class SeventhTest
    {
        public void DoTest()
        {
            领导 朱哥 = new 领导();
            下属 小薇 = new 下属();

            朱哥.增加任务(小薇.自己的工作, "运营魔兽世界");
            朱哥.处理任务();

            Console.ReadLine();
            朱哥.增加任务(小薇.自己的工作, "处理业内竞争");
            朱哥.处理任务();
        }

    }

    delegate string 委托任务(string 任务内容);

    class 领导
    {
        private Hashtable 任务列表;

        public void 增加任务(委托任务 一个任务, string 任务类型)
        {
            if(任务列表 == null)
                任务列表 = new Hashtable();
            任务列表[任务类型] = 一个任务;
        }

        public void 处理任务()
        {
            foreach(DictionaryEntry 任务项 in 任务列表)
            {
                string 结果 = ((委托任务)任务项.Value)((string)任务项.Key);
                Console.WriteLine(结果);
            }
        }

    }

    class 下属
    {
        public string 自己的工作(string 任务内容)
        {
            StringBuilder 工作内容 = new StringBuilder();
            if (任务内容 == "运营魔兽世界")
            {
                工作内容.AppendLine("安排设备采购");
                工作内容.AppendLine("招募客服,上岗培训");
                工作内容.AppendLine("广告宣传");
                工作内容.AppendLine("游戏上市");
                工作内容.AppendLine("推出活动");
                工作内容.AppendLine("…………");
            }
            else if (任务内容 == "处理业内竞争")
            {
                工作内容.AppendLine("调查竞争对手");
                工作内容.AppendLine("展开斗争");
            }
            return 工作内容.ToString();
        }

    }

    // 上一例,领导将自己做的事情向外公开,下属对领导公开的事情做进一步处理.
    // 这个例子,领导接收外部的事情,并处理.
    // 一个是向外开放,一个是向内接收.
}

posted @ 2010-12-12 22:07  规定  阅读(763)  评论(3编辑  收藏  举报