private void buttonUsingADelegate_Click(object sender, EventArgs e) { Console.WriteLine("\n**** Using A Delegate Demo ****\n"); //Like C++ you can use a delegate to point to a Static method... MethodPointer1 objMP_A = new MethodPointer1(MyMethodPointerDemoClass.StaticMethod); Console.WriteLine(objMP_A.Invoke("Test1\n")); //UN-Like C++ you can also use a delegate to point to a Instance method... MyMethodPointerDemoClass objC1 = new MyMethodPointerDemoClass(); MethodPointer1 objMP_B = new MethodPointer1(objC1.InstanceMethod); Console.WriteLine(objMP_B.Invoke("Test2\n")); //You can also "Invoke" a delegate by simply using it like a method call... Console.WriteLine(objMP_B("Test3\n")); //Using a Delegate, really creates an Invisible class with useful Meta-Data. //the new class inherits from the base class called System.MulticastDelegate System.Reflection.MethodInfo objMI = objMP_B.Method; Console.WriteLine("\n**** Meta-Data ****\n"); Console.WriteLine("\tMethod Name: {0} ", objMI.Name); Console.WriteLine("\tMethod ReturnType: {0} ", objMI.ReturnType.ToString()); Console.WriteLine("\tMethod Attributes: {0} ", objMI.Attributes.ToString()); Console.WriteLine("\tMethod IsConstructor: {0} ", objMI.IsConstructor.ToString()); }
private void buttonMulticasting_Click(object sender, EventArgs e) { Console.WriteLine("\n**** Multi Casting with Delegates Demo ****\n"); MethodPointer1 objMP_D = MyMethodPointerDemoClass.StaticMethod;//Don't use the "+" sign for the first one objMP_D += new MyMethodPointerDemoClass().InstanceMethod; //Use the "+" sign to connect additional ones // You can fire all methods with one call if the underlining invisible Delegate class // supports it. Since .NET 4.0 delegates inherit from System.MulticastDelegate // expect them to multicast. Console.WriteLine(objMP_D.Invoke("\nCalling only the last method hooked up!\n")); //If not, then you execute non-multicast delegates like this... Console.WriteLine("\nUsing a loop to execute all methods\n"); if (objMP_D != null) { foreach (MethodPointer1 p in objMP_D.GetInvocationList()) { Console.WriteLine("\t" + p.Invoke("Now Calling => " + p.Method.Name)); } } }