通过名称获取EventHandler? [英] Get EventHandler by name?
问题描述
如果还有另一个问题可以解释这一点,我为找不到它而表示歉意,但我认为这可能与我不熟悉与我尝试做的事情有关的某些术语有关.
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.
我想做的是按名称向按钮添加事件处理程序.因此,例如,在下面的代码中,我不知道要添加showInfo,而是可以通过名称(字符串)(例如"showInfo")引用EventHandler吗?
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)
{
// ..
}
推荐答案
您可以通过反射从方法创建委托,然后通过反射将其订阅到事件,是的.示例代码:
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();
}
}
这篇关于通过名称获取EventHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!