我想要编写一个可重用的函数通过反射引发事件。
经过搜索,我发现了这个类似的问题:如何在 .NET/C# 中通过反射引发事件? https://stackoverflow.com/questions/198543/how-do-i-raise-an-event-via-reflection-in-net-c
它一直有效,直到我向 WinForm 控件注册事件处理程序并尝试调用它。私人领域’<EventName>
’就这样消失了。
下面是我的简化代码,它重现了该问题:
程序.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 !!!!!!!!!!!");
}
这是我的 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 static MethodInfo GetEventInvoker(object obj, string eventName)
{
// --- Begin parameters checking code -----------------------------
Debug.Assert(obj != null);
Debug.Assert(!string.IsNullOrEmpty(eventName));
// --- End parameters checking code -------------------------------
// prepare current processing type
Type currentType = obj.GetType();
// try to get special event decleration
while (true)
{
FieldInfo fieldInfo = currentType.GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField);
if (fieldInfo == null)
{
if (currentType.BaseType != null)
{
// move deeper
currentType = currentType.BaseType;
continue;
}
Debug.Fail(string.Format("Not found event named {0} in object type {1}", eventName, obj));
return null;
}
// found
return ((MulticastDelegate)fieldInfo.GetValue(obj)).Method;
}
}
附加信息:
- 同班活动:有效。
- 不同类中的事件,同一程序集中的子类:有效。
- 活动于MY不同的组装、调试和发布模式:有效。
- WinForm、DevExpress 中的事件...:不起作用
任何帮助表示赞赏。
WinForms 中的事件通常会被覆盖,并且没有一对一的委托支持。相反,该类(基本上)具有事件->委托映射的字典,并且仅在添加事件时才创建委托。因此,一旦您通过反射访问该字段,就不能假设有委托支持该事件。
编辑:这会遇到同样的问题,但比将其作为字段并进行投射要好。
var eventInfo = currentType.GetEvent(eventName);
var eventRaiseMethod = eventInfo.GetRaiseMethod()
eventRaiseMethod.Invoke()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)