EventHandler 的用法

using System;
using System.Collections.Generic;

//---------------------------------------------------------
public class MyEventArgs : EventArgs
{
   private string msg;

   public MyEventArgs(string messageData)
   {
      msg = messageData;
   }
   public string Message
   {
      get { return msg; }
      set { msg = value; }
   }
}
//---------------------------------------------------------
public class HasEvent
{
   // Declare an event of delegate type EventHandler of 
   // MyEventArgs.

   public event EventHandler SampleEvent;

   public void DemoEvent(string val)
   {
      // Copy to a temporary variable to be thread-safe.
      EventHandler temp = SampleEvent;
      if (temp != null)
         temp(this, new MyEventArgs(val));
   }
}
//---------------------------------------------------------
public class Example
{
   private static System.Windows.Controls.TextBlock outputBlock;

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {

      Example.outputBlock = outputBlock;
      HasEvent he = new HasEvent();
      he.SampleEvent +=
                 new EventHandler(ExampleEventHandler);
      he.DemoEvent("Hey there, Bruce!");
      he.DemoEvent("How are you today?");
      he.DemoEvent("I'm pretty good.");
      he.DemoEvent("Thanks for asking!");
   }
   private static void ExampleEventHandler(object src, MyEventArgs mea)
   {
      outputBlock.Text += mea.Message + "/n";
   }
}
//---------------------------------------------------------
/*
This example produces the following results:

Hey there, Bruce!
How are you today?
I'm pretty good.
Thanks for asking!

*/

你可能感兴趣的:(EventHandler 的用法)