Get EventHandler by name?

偶尔善良 提交于 2019-12-12 03:16:17

问题


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();
    }    
}


来源:https://stackoverflow.com/questions/10661102/get-eventhandler-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!