Get EventHandler by name?

2019-08-24 07:53发布

问题:

if there is another question that explains this I apologize for not being able to find it, but I think it might have to do with my unfamiliarity with some of the terms involved with what I'm trying to do.

What I'm trying to do is to add an eventhandler to a button by name. So for example, in the code below instead of knowing that I want to add showInfo, can I reference the EventHandler by name (string) like "showInfo"?

myButton.Click += new EventHandler(showInfo);

void showInfo(object sender, EventArgs e)
{
    // ..
}

回答1:

You can create a delegate from a method via reflection, and then subscribe that to the event via reflection, yes. Sample code:

using System;
using System.Reflection;

class Publisher
{
    public event EventHandler Foo;

    public void RaiseFoo()
    {
        EventHandler handler = Foo;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

class Subscriber
{
    public void HandleEvent(object sender, EventArgs e)
    {
        Console.WriteLine("In HandleEvent");
    }
}

class Test
{
    static void Main()
    {
        var subscriber = new Subscriber();
        var publisher = new Publisher();

        var methodInfo = typeof(Subscriber).GetMethod("HandleEvent");
        var handler = (EventHandler) Delegate.CreateDelegate(
               typeof(EventHandler), subscriber, methodInfo);

        var eventInfo = typeof(Publisher).GetEvent("Foo");
        eventInfo.AddEventHandler(publisher, handler);

        publisher.RaiseFoo();
    }    
}