Demonstrate getting and printing the invocation list for a delegate

image_pdfimage_print

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// InvkList.cs -- Demonstrate getting and printing the invocation list
//                for a delegate.
//
//                Compile this program with the following command line:
//                    C:>csc InvkList.cs
using System;
using System.Reflection;

namespace nsDelegates
{
    public class DelegatesList
    {
        public delegate void ListHandler ();
        public ListHandler DoList;
        static public void Main ()
        {
            DelegatesList main = new DelegatesList ();
            main.DoList += new ListHandler (DelegateMethodOne);
            main.DoList += new ListHandler (DelegateMethodThree);
            main.DoList += new ListHandler (DelegateMethodTwo);
            Delegate [] dlgs = main.DoList.GetInvocationList ();
            foreach (Delegate dl in dlgs)
            {
                MethodInfo info = dl.Method;
                Console.WriteLine (info.Name);
                info.Invoke (main, null);
            }
        }
        static void DelegateMethodOne ()
        {
            Console.WriteLine ("In delegate method one");
        }
        static void DelegateMethodTwo ()
        {
            Console.WriteLine ("In delegate method two");
        }
        static void DelegateMethodThree ()
        {
            Console.WriteLine ("In delegate method three");
        }
    }
}