Tha*_*ran 6 c# reflection events
我想编写一个可重用的函数来通过反射来引发事件.
搜索之后,我发现了类似的问题:如何通过.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 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;
}
}
Run Code Online (Sandbox Code Playgroud)
附加信息:
任何帮助表示赞赏.
WinForms 中的事件通常会被覆盖,并且没有一对一的委托支持。相反,该类(基本上)具有事件->委托映射的字典,并且仅在添加事件时才创建委托。因此,一旦您通过反射访问该字段,就不能假设有委托支持该事件。
编辑:这会遇到同样的问题,但比将其作为字段并进行投射要好。
var eventInfo = currentType.GetEvent(eventName);
var eventRaiseMethod = eventInfo.GetRaiseMethod()
eventRaiseMethod.Invoke()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6782 次 |
| 最近记录: |