Generic events : Generic Event « GUI Windows Forms « C# / CSharp Tutorial






using System;  
  
class MyEventArgs : EventArgs {  
  public int eventnum;  
}  
 
delegate void MyEventHandler<T, V>(T source, V args); 
  
class MyEvent {  
  static int count = 0;  
  
  public event MyEventHandler<MyEvent, MyEventArgs> SomeEvent;  
  
  public void OnSomeEvent() {  
    MyEventArgs arg = new MyEventArgs();  
  
    if(SomeEvent != null) {  
      arg.eventnum = count++;  
      SomeEvent(this, arg);  
    }  
  }  
}  
  
class KeyBorardEventHandler {  
  public void handler<T, V>(T source, V arg) where V : MyEventArgs {  
    Console.WriteLine("Event " + arg.eventnum +  
                      " received by an KeyBorardEventHandler object.");  
    Console.WriteLine("Source is " + source);  
    Console.WriteLine();  
  }  
}  
  
class MouseEventHandler {   
  public void handler<T,V>(T source, V arg) where V : MyEventArgs {  
    Console.WriteLine("Event " + arg.eventnum +  
                      " received by a MouseEventHandler object.");  
    Console.WriteLine("Source is " + source);  
    Console.WriteLine();  
  }  
}  
 
class UseGenericEventDelegate {  
  public static void Main() {   
    KeyBorardEventHandler ob1 = new KeyBorardEventHandler();  
    MouseEventHandler ob2 = new MouseEventHandler();  
    MyEvent evt = new MyEvent();  
  
    // Add handler() to the event list.  
    evt.SomeEvent += ob1.handler;  
    evt.SomeEvent += ob2.handler;  
  
    // Fire the event.  
    evt.OnSomeEvent();  
    evt.OnSomeEvent();  
  }  
}
Event 0 received by an KeyBorardEventHandler object.
Source is MyEvent

Event 0 received by a MouseEventHandler object.
Source is MyEvent

Event 1 received by an KeyBorardEventHandler object.
Source is MyEvent

Event 1 received by a MouseEventHandler object.
Source is MyEvent








23.66.Generic Event
23.66.1.Get event source from event arguments
23.66.2.Generic events