我想编写一个可重用的函数来通过反射来引发事件.
搜索之后,我发现了类似的问题:如何通过.NET/C#中的反射来引发事件?
它一直有效,直到我向WinForm控件注册一个事件处理程序并尝试调用它.私人领域' <EventName>'简直消失了.
下面是我的简化代码,它可以重现问题:
Program.cs中:
public static void Main()
{
Control control = new Control();
control.Click += new EventHandler(control_Click);
MethodInfo eventInvoker = ReflectionHelper.GetEventInvoker(control, "Click");
eventInvoker.Invoke(control, new object[] {null, null});
}
static void control_Click(object sender, EventArgs e)
{
Console.WriteLine("Clicked !!!!!!!!!!!");
}
Run Code Online (Sandbox Code Playgroud)
这是我的ReflectionHelper类:
public static class ReflectionHelper
{
/// <summary>
/// Gets method that will be invoked the event is raised.
/// </summary>
/// <param name="obj">Object that contains the event.</param>
/// <param name="eventName">Event Name.</param>
/// <returns></returns>
public …Run Code Online (Sandbox Code Playgroud)