通过代码学习C#中的事件

通过代码学习C#中的事件

 

namespace DotNetEvents

{

    using System;

    using System.Collections.Generic;

 

    //定义一个用于传递信息的类

    public class CustomEventArgs : EventArgs

    {

        public CustomEventArgs(string s)

        {

            message = s;

        }

        private string message;

 

        public string Message

        {

            get { return message; }

            set { message = value; }

        }

    }

 

    // 定义一个能够发布事件的类

    class Publisher

    {

 

        // 通过泛型的方式定义一个事件

        public event EventHandler<CustomEventArgs> RaiseCustomEvent;

 

        public void DoSomething()

        {

           //激发事件

            OnRaiseCustomEvent(new CustomEventArgs("Did something"));

 

        }

 

      //封装事件激发代码

        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)

        {

          

            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

 

            // Event will be null if there are no subscribers

            if (handler != null)

            {

                // Format the string to send inside the CustomEventArgs parameter

                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

 

                //采用()调用的方式激发事件

                handler(this, e);

            }

        }

    }

 

//订阅事件的类

    class Subscriber

    {

        private string id;

        public Subscriber(string ID, Publisher pub)

        {

            id = ID;

            // Subscribe to the event using C# 2.0 syntax

            pub.RaiseCustomEvent += HandleCustomEvent;

        }

 

        //响应事件函数

        void HandleCustomEvent(object sender, CustomEventArgs e)

        {

            Console.WriteLine(id + " received this message: {0}", e.Message);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Publisher pub = new Publisher();

            Subscriber sub1 = new Subscriber("sub1", pub);

            Subscriber sub2 = new Subscriber("sub2", pub);

 

            // Call the method that raises the event.

            pub.DoSomething();

 

            // Keep the console window open

            Console.WriteLine("Press Enter to close this window.");

            Console.ReadLine();

 

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值