你会如何用反射调用事件?

时间:2012-10-09 20:57:38

标签: c# .net class events event-handling

假设我有一个专门用于指定C#事件的类,我将这个类传递给我的应用程序。

public class MyEvents
{
    public event MyEventHandler OnBeforeSomeAction;
    public event MyEventHandler OnSomeAction;
}

为了调用这些事件,调用必须来自类本身。让其他类触发这些事件的简单方法MyEvents在应用程序中传递将是创建公共触发器函数。

public class MyEvents
{
    public event MyEventHandler OnBeforeSomeAction;
    public event MyEventHandler OnSomeAction;

    public void TriggerOnBeforeSomeAction()
    {
        OnBeforeSomeAction();
    }

    public void TriggerOnSomeAction()
    {
        OnSomeAction();
    }
}

但是,如果此类上有许多事件,那么还必须有许多触发方法。是否有办法使用反射获取事件并触发它?像这样:

public class MyEvents
{
    public event MyEventHandler OnBeforeSomeAction;
    public event MyEventHandler OnSomeAction;

    public void TriggerEvent(string eventName)
    {
        var event = // some magic reflection.
        event.Invoke();
    }
}

1 个答案:

答案 0 :(得分:2)

正是你想要的 - 取自this fantastic page ....

    public void TriggerEvent(string handler, EventArgs e)
    {
        MulticastDelegate eventDelegate =
              (MulticastDelegate)this.GetType().GetField(handler,
               System.Reflection.BindingFlags.Instance |
               System.Reflection.BindingFlags.NonPublic).GetValue(this);

        Delegate[] delegates = eventDelegate.GetInvocationList();

        foreach (Delegate dlg in delegates)
        {
            dlg.Method.Invoke(dlg.Target, new object[] { this, e });
        } 
    }