Description



Description

Events are handled by delegates. An event listener supplies an event-handler delegate that is invoked whenever the event is raised by an event source. In order to connect to the event source, the event listener adds this delegate to the invocation list of the source. When the event is raised, the event-handler delegate invokes the methods in its invocation list. The GetAddMethod, AddEventHandler, GetremoveMethod, and RemoveEventHandler methods, and the delegate type of the event-handler associated with an event, are required to be marked in the metadata.

[Note: For information on delegates, see the System.Delegate class overview.]

[Note: For information on events, see Partitions I and II of the CLI specification.]

Example

using System;

using System.Reflection;



/// <summary>

/// This example shows how to print out an Event in C# syntax

/// </summary>



public class EventInfoSample

{

    public static void Main()

    {

        Type type = typeof(Assembly);



        foreach (EventInfo evnt in type.GetEvents(BindingFlags.NonPublic | 

            BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))

        {

            //All events should at least have an add method, if not, skip it

            if (evnt.GetAddMethod() == null)

            {

                continue;

            }



            //Skip any events that are not publicly accessible.  

            //Note: BindingFlags.NonPublic include protected as well 

            //private members

            MethodInfo addMethod = evnt.GetAddMethod();

            if (!(addMethod.IsPublic ||

                addMethod.IsFamily ||

                addMethod.IsFamilyOrAssembly))

            {

                return;

            }



            if (addMethod.IsPublic)

            {

                Console.Write("public ");

            }

            else if (addMethod.IsFamily)

            {

                Console.Write("protected ");

            }

            else if (addMethod.IsFamilyOrAssembly)

            {

                Console.Write("protected internal ");

            }



            Console.Write("event ");

            Console.Write(evnt.EventHandlerType.Name);

            Console.Write(" ");

            Console.Write(evnt.Name);

            Console.WriteLine(";");

        }

        Assembly a = Assembly.GetAssembly(typeof(object));

        EventInfo e = type.GetEvent("ModuleResolve");

        e.AddEventHandler(a, new ModuleResolveEventHandler(ModuleResolver));

        Console.WriteLine();

        Console.WriteLine();

        Console.WriteLine("Press Enter to continue");

        Console.ReadLine();

    }

    static Module ModuleResolver(object sender, ResolveEventArgs e)

    {

        //TODO: insert code to handle event

        return null;

    }





} //end class


The output is


public event ModuleResolveEventHandler ModuleResolve;





Press Enter to continue