C# 委托链使用

C# 委托链使用
2010-07-11 10:24 A.M.

之前已经介绍过委托链,下面这个是关于委托链的拓展。

using System;


namespace DelegateTest
{
    delegate void EatDelegate(string food);
    class Party
    {
        //声明一个参数可变的方法
        static void eatToghter(string food, params EatDelegate[] values)
        {
            if (values == null)
            {
                Console.WriteLine("座谈会结束");
            }
            else
            {
                //声明委托链
                EatDelegate eatChain = null;
                //将委托链接起来
                foreach (EatDelegate ed in values)
                {
                    eatChain += ed;
                }
                eatChain(food);
                Console.WriteLine();
            }
        }
        static void Main(string[] args)
        {
            Man Zs = new Man("张三");
            Man Ls = new Man("李四");
            Man Ww = new Man("王五");
            EatDelegate zs = new EatDelegate(Zs.eat);
            EatDelegate ls = new EatDelegate(Ls.eat);
            EatDelegate ww = new EatDelegate(Ww.eat);

            Console.WriteLine("张三,李四,王五开座谈会");
            eatToghter("西瓜", zs, ls, ww);
            Console.WriteLine("李四出去接电话");
            eatToghter("香蕉", zs, ww);
            Console.WriteLine("李四回来了");
            eatToghter("桔子", zs, ls, ww);
            eatToghter(null, null);

            Console.ReadKey();
        }
    }
    //产生人类
    class Man
    {
        private string name;
        public Man(string name)
        {
            this.name = name;
        }
        public void eat(string food)
        {
            Console.WriteLine(name + "吃" + food);
        }
    }
}

效果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值