支付宝
微信
扫描二维码打赏
更多详情(暂无)

C#中的事件委托

C#中的事件与委托,对于我们写业务代码的程序员来说不常用,这就会导致经常忘记,这边再温习一下。

 

    //委托
    public delegate void MyEventDelegateHandler(string msg);

    //发布者
    public class MyService
    {
        public event MyEventDelegateHandler hanldes;

        public void Send(string msg)//发布者的发布方法
        {
            Console.WriteLine("发布者发布信息:" + msg);
            if (hanldes != null)
                hanldes(msg);//转给订阅者
        }
    }
    //订阅者
    public class MyClient
    {
        public void Receive(string msg)
        {
            Console.WriteLine("订阅者接收到信息:" + msg);
        }
    }

调用方法

  MyService service = new MyService();
            MyClient client = new MyClient();
            service.hanldes += new MyEventDelegateHandler(client.Receive);//添加事件
            service.hanldes -= client.Receive;//删除事件
            service.hanldes+=new MyEventDelegateHandler(client.Receive);
            service.hanldes += (string msg) => Console.WriteLine("匿名接收者接收到信息:" + msg);          
            service.Send("消息是SBSBSB");

            Console.WriteLine();

            //C#中定义好的委托 还有Func(带返回值的)
            Action<string> action = new Action<string>(client.Receive);
            action("huage");

            action = (string msg) => client.Receive(msg);
            action("huage");    

  

编程之余,多多思考,多多学习,有助于开发智商啊

posted @ 2019-10-12 15:16  华临天下  阅读(752)  评论(0编辑  收藏  举报