订阅与反思的事件 [英] Subscribe to an event with Reflection
问题描述
我有一个非常简单的类:
I have a very simple class :
class Trace
{
void WriteTrace()
{
Console.WriteLine("Trace !");
}
}
我想这个类订阅事件,例如表单控件的加载事件。控制和事件是动态定义,所以我想使用反射来做到这一点,我想这样的事情:
I want this class subscribes to an event, for example the load event of a form control. The control and event are define dynamically so I want to use reflection to do this I'm trying something like that :
在我的课堂跟踪我有这样的方法:
In my class Trace I have this method :
public void SubscribeEvent (Control control)
{
if (type.IsAssignableFrom(control.GetType()))
{
Trace test = this;
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
// Subscribe to the event
EventInfo eventInfo = control.GetType().GetEvent("Load"); // We suppose control is a form
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, control, method); // ERROR : Error binding to target method
}
}
}
对所用的最后一行的错误:错误结合靶的方法。什么是错在我的代码片段?
There is an error on the last line : Error binding to target method. What's wrong in my snippet ?
感谢您!
修改:好吧,有没有更多的错误,但在该事件装载从形式提出,该方法WRITETRACE不叫(我已经把一个断点,但没有达到) 。为什么呢?
EDIT : Ok, there is no more error but when the event "Load" is raised from the Form, the method WriteTrace is not called (I have put a breakpoint but there is not reached). Why ?
抱歉编辑,它的工作原理很细的:)
Sorry for the edit, it works very fine :)
推荐答案
有了一些变化,我能够执行你的样品。
With a few changes, I was able to execute your sample.
首先,在跟踪
的方法必须有一个不同的签名与事件处理程序
键入是:
Firstly, the method on Trace
must have a different signature to correspond with the EventHandler
type:
public class Trace
{
public void WriteTrace(object sender, EventArgs e)
{
Console.WriteLine("Trace !");
}
}
其次,一些变化所提出的 SubscribeEvent
:
public void SubscribeEvent(Control control)
{
if (typeof(Control).IsAssignableFrom(control.GetType()))
{
Trace test = this;
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
EventInfo eventInfo = control.GetType().GetEvent("Load");
// Create the delegate on the test class because that's where the
// method is. This corresponds with `new EventHandler(test.WriteTrace)`.
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
// Assign the eventhandler. This corresponds with `control.Load += ...`.
eventInfo.AddEventHandler(control, handler);
}
}
我希望这有助于。
I hope this helps.
这篇关于订阅与反思的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!