天天看点

C#委托详解实例

首先看一个例子,一名律师代表三名员工向老板讨薪

员工将讨薪方法委托为律师

涉及到三个对象:员工,老板,律师

/// <summary>
    /// 员工
    /// </summary>
    class Employee {
        public string name;
        public int money;

        public Employee() { }
        public Employee(string name, int money) {
            this.name = name;
            this.money = money;
        }
        /// <summary>
        /// 员工有讨薪的权利,也就是有这个方法
        /// </summary>
        public void GetMoney(Boss b) {
            Console.WriteLine("我是{0},{1}还我血汗钱{2}",name,b.name,money);
        }
    }

           
/// <summary>
/// 老板
/// </summary>
class Boss {
        public string name;
        public Boss(string name) {
            this.name = name;
        }
    }
           

//创建一个讨薪的委托

delegate void GetMoneyDele(Boss boss)

/// <summary>
 /// 律师
 /// </summary>
 class Lawyee {
        public string name;
        public Lawyee(string name) {
            this.name = name;
        }
        GetMoneyDele getMoneyDele = null;
        Boss target = null;
        /// <summary>
        /// 员工将讨薪方法委托为律师
        /// 1.需要获取员工的讨薪方法:将方法当成一个参数进行传递
        /// 2.方法所需要参数也需要传进来
        /// </summary>
        public void AddGetMoney(GetMoneyDele dele,Boss boss) {
            if (getMoneyDele == null)
            {
                getMoneyDele = new GetMoneyDele(dele);
                target = boss;
            }
            else {
                getMoneyDele += dele;
            }
        }

        /// <summary>
        /// 律师开始讨薪了:执行委托
        /// </summary>
        public void GetMoney() {
            getMoneyDele(target);
        }

    }
           
static void Main(string[] args)
        {
            //Boss类:老板类
            //Lawyee类:律师类
            //Employee员工类:
            //员工张三、李四、王五委托律师赵六律师跟Boss田七讨薪

            Boss zj = new Boss("zj");

            Employee zhangsan = new Employee("张三", 10000);
            Employee lisi = new Employee("李四", 12000);
            Employee wangwu = new Employee("王五", 22000);

            //zhangsan.GetMoney(zj);
            //lisi.GetMoney(zj);
            //wangwu.GetMoney(zj);
            Lawyee zhaoliu = new Lawyee("赵六");
            zhaoliu.AddGetMoney(zhangsan.GetMoney, zj);
            zhaoliu.AddGetMoney(lisi.GetMoney, zj);
            zhaoliu.AddGetMoney(wangwu.GetMoney, zj);
            zhaoliu.GetMoney();
            Console.ReadLine();
        }