Freigeben über


Invoke Method by Name

Did you ever wonder how AutoEventWireup="true" works in ASP.NET Pages? The page class basically hooks different generic event handler methods to the page life-cycle.
Such as Page_Load Method get’s called if present. OK!! It’s called using reflection.

public partial class_Default: System.Web.UI.Page
{
    protected voidPage_Load(objectsender, EventArgs e)
    {

    }
}

 

You can use a delegate or MethodInfo object to invoke method with a known signature. Here is a quick test that shows how do you do such in your code

Out test  :

 using System;

namespace ConsoleApplication1
{
    class Program
    {
        delegate string TestMessageHandler(string s);

        static void Main(string[] args)
        {
            Delegate dl = Delegate.CreateDelegate(
                typeof(TestMessageHandler),
                typeof(Program),
                "SayHi");

            Console.WriteLine(dl.DynamicInvoke("Bill"));
            Console.ReadLine();
        }
        
        public static string SayHi(string name)
        {
            return "Welcome " + name;
        }        
    }
}

Even you can make this more strongly typed by casting the resulting Delegate object of Delegate.CreateDelegate  to the target delegate (TestMessageHandler)

Have fun..