首页 > 代码库 > 事件2 (标准 EventHandler)

事件2 (标准 EventHandler)

  • EventHandler: 能提供一个对于所有事件和事件处理器都通用的签名,只允许两个参数,(而不是各自都有不同签名)
    • Object sender , //用来保存除非时间的对象引用,由于为object类型的,所以可以匹配任何类型的参数
    • EventArgs e , //用来保存状态信息,(或用户传递数据,需继承该类)

      namespace System

      {

      // Summary:

      // Represents the method that will handle an event.

      //

      // Parameters:

      // sender:

      // The source of the event.

      //

      // e:

      // An System.EventArgs that contains the event data.

      //

      // Type parameters:

      // TEventArgs:

      // The type of the event data generated by the event.

      [Serializable]

      public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e); //注意这个是模板

      }

      ? ??

    • EventArgs

      namespace System

      {

      // Summary:

      // System.EventArgs is the base class for classes containing event data.

      [Serializable]

      [ComVisible(true)]

      public class EventArgs

      {

      // Summary:

      // Represents an event with no event data.

      public static readonly EventArgs Empty;

      ? ??

      // Summary:

      // Initializes a new instance of the System.EventArgs class.

      public EventArgs();

      }

      }

    • 扩展EventArgs来传递数据

      技术分享

      ? ??

      /////////////////////////////////////////////////////////////////

    • 示例:

      public class IncrementerEventArgs : EventArgs // Custom class derived from EventArgs

      {

      public int IterationCount { get; set; } // Stores an integer

      }

      ? ??

      class Incrementer

      {

      public event EventHandler<IncrementerEventArgs> CountedADozen;

      ? ??

      public void DoCount()

      {

      IncrementerEventArgs args = new IncrementerEventArgs();

      for ( int i=1; i < 100; i++ )

      if ( i % 12 == 0 && CountedADozen != null )

      {

      args.IterationCount = i;

      CountedADozen( this, args );

      }

      }

      }

      ? ??

      class Dozens

      {

      public int DozensCount { get; private set; }

      ? ??

      public Dozens( Incrementer incrementer )

      {

      DozensCount = 0;

      incrementer.CountedADozen += IncrementDozensCount;

      }

      ? ??

      void IncrementDozensCount( object source, IncrementerEventArgs e )

      {

      Console.WriteLine( "Incremented at iteration: {0} in {1}",

      e.IterationCount, source.ToString() );

      DozensCount++;

      }

      }

      ? ??

      class Program

      {

      static void Main()

      {

      Incrementer incrementer = new Incrementer();

      Dozens dozensCounter = new Dozens( incrementer );

      ? ??

      incrementer.DoCount();

      Console.WriteLine( "Number of dozens = {0}",

      dozensCounter.DozensCount );

      }

      }

    • ?

事件2 (标准 EventHandler)