C#中的事件

来源:互联网 发布:中电科软件与硬件工资 编辑:程序博客网 时间:2024/04/30 15:15

C#中的事件集合了事件数据和引用订阅匹配的方法以及事件触发方式的集合,一般是一个类。

  1.事件数据在C#中都必须继承EventArgs类

  2.引用订阅匹配的方法都通过Delegate生命

  3.触发方式一般都在时间内部类中自定义

  4.事件一般包含在一个类中,这个类一般还有触发事件的方式。

  5.事件订阅

  6.事件使用

例如:

  1.事件数据:

         public class MyEventArgs : EventArgs
      {
        public string message;
        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                message = value;
            }
        }
        public MyEventArgs(string str)
        {
            Message = str;
        }
    }

 2.引用订阅匹配的方法
    public delegate void MyDelegate(object sender,MyEventArgs e);

3.包含事件的类也即事件发布者
    public class Publish
    {
        public event MyDelegate MyEvent;
        public void RaiseEvent()
        {
            MyEventArgs e = new MyEventArgs("Hello Wolrd");
            if (MyEvent != null)
            {
                MyEvent(this, e);
            }
        }
    }

4.事件订阅者

      public class Subscriber
    {
        private string id;
        public Subscriber(string id, Publish publisher)
        {
            this.id = id;
            publisher.MyEvent += new MyDelegate(publisher_MyEvent);
        }
        public void publisher_MyEvent(object sender, MyEventArgs e)
        {
            Console.WriteLine(id + "received this message:{0}", e.Message);
        }
    }

5.事件使用

    class Program
    {
        static void Main(string[] args)
        {
            Publish pub = new Publish();
            Subscriber sub1 = new Subscriber("sub1", pub);
            Subscriber sub2 = new Subscriber("sub2", pub);
            pub.RaiseEvent();
            Console.WriteLine("Press Enter to close this window");
            Console.ReadLine();
        }
    }

原创粉丝点击