事件机制(复习)

最近写了几个控件,继承Control的组件。

再次体会了下.net的event的含义

1,定义事件参数

   class myEventArgs:EventArgs

     {

         里面可以定义事件参数的属性;(e)

     }

  2,定义事件类

   class myEventClass

   {

        MyEventArgs _eventArgs = new MyEventArgs();

        delegate void EventHandler(object sender, MyEventArgs e);

        event EventHandler ReciveData;

  public void OnReciveData(MyEventArgs e)
  {
    EventHandler handler = ReciveData;
    if (handler != null) handler(this, e);
  }

   }

3,调用

static void Main(string[] args)
{
  var eventsource=new EventSource();

  eventsource.ReciveData += EventsourceReciveData;
  MyEventArgs myargs = new MyEventArgs("good1")
  eventsource.OnReciveData(myargs);
  Console.Read();
}

private static void EventsourceReciveData(object sender, MyEventArgs e)
{
    Console.WriteLine(e.GetMyData()) ;
}

  

什么时候触发这个事件呢?

事件:由引发着引发时所要发生的一系列动作

这里,在主函数中调用了一次事件,所以每次主函数执行都会执行一次Event,

之前一直不敢用event,因为不知道什么时候要出发

比如button,单击的时候会被触发。

原文地址:https://www.cnblogs.com/anbylau2130/p/3165363.html