Examining Events


As you saw in Chapter 9, "Events and Delegates," events are an extremely powerful feature that work with delegates that match a specific method signature to signal important events. You can then "add" your delegate to an event hosted by another class. When that event is triggered, your delegate will be among those methods invoked as a result. In this way, you can write code that will subscribe to be notified when important changes take place or important events need to be signaled.

Using reflection, you can dynamically obtain information about an event at runtime.

The code in Listing 11.3 shows how to use the EventInfo class to obtain detailed information about an event, as well as add and remove event handlers. A new delegate and an event called OnPropertyChanged were added to the original Customer class used in the first sample for the purpose of this demonstration.

Listing 11.3. Reflecting on Events

using System; using System.Reflection; using System.Collections.Generic; using System.Text; namespace EventInfoDemo { class Program { static void Main(string[] args) {     ReflectMethods.Customer<string> cust = new ReflectMethods.Customer<string>();     ReflectMethods.PropertyChangedDelegate propDel = new ReflectMethods.PropertyChangedDelegate(cust_OnPropertyChanged);     cust.OnPropertyChanged += propDel;     EventInfo evt = cust.GetType().GetEvent("OnPropertyChanged");     Console.WriteLine("Event {0}:", evt.Name);     Console.WriteLine("\tMulticast?: {0}", evt.IsMulticast);     Console.WriteLine("\tModule: {0}", evt.Module.Name);     MethodInfo addMethod = evt.GetAddMethod();     Console.WriteLine("\tAdd Method: {0}", addMethod.ToString());     Console.WriteLine("\tRemove Method: {0}", evt.GetRemoveMethod().ToString());     cust.PubData = 99;     evt.RemoveEventHandler(cust, propDel) ;     cust.PubData = 42;     evt.AddEventHandler(cust, propDel);     evt.AddEventHandler(cust, propDel);     cust.PubData = 150;     Console.ReadLine(); } static void cust_OnPropertyChanged(string propName, int value) {     Console.WriteLine("Customer Property changed : {0}, {1}", propName, value); } } } 



Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net