通过反射c#添加和删除事件处理程序

本文关键字:删除 事件处理 程序 添加 反射 | 更新日期: 2023-09-27 18:08:13

大家好!我的目的是实现一个类,它将允许我们对事件订阅和取消订阅对象。这是我的类的代码。

public static class EventSubscriber
{
    public static void AddEventHandler(EventInfo eventInfo, object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.AddEventHandler(item, handler);
    }
    public static void RemoveEventHandler(EventInfo eventInfo,
                        object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.RemoveEventHandler(item, handler);
    }
    private static ParameterExpression[] GetParameters(EventInfo eventInfo)
    {
        return eventInfo.EventHandlerType
          .GetMethod("Invoke")
          .GetParameters()
          .Select(parameter => Expression.Parameter(parameter.ParameterType))
          .ToArray();
    }
    private static Delegate GetHandler(EventInfo eventInfo,
                Action action, ParameterExpression[] parameters)
    {
        return Expression.Lambda(
            eventInfo.EventHandlerType,
            Expression.Call(Expression.Constant(action),
                      "Invoke", Type.EmptyTypes), parameters)
          .Compile();
    }
}

正如你所看到的,这里有两个公共方法,它们实际上订阅和取消订阅(from)事件的对象。这是我测试它的例子

class Program
{
    static void Main()
    {
        Test test = new Test();
        test.SubscribeTimer();
        while (true)
        {
            if(test.a == 10)
            {
                break;
            }
        }
        test.UnsubscribeTimer();
        while (true)
        {
        }
    }
}
class Test
{
    System.Timers.Timer timer;
    public int a = 0;
    public Test()
    {
        timer = new System.Timers.Timer(1000);
        timer.Start();
    }
    public void SubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerNotElapsed);
    }
    public void UnsubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerNotElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerElapsed);
    }
    public void TimerElapsed()
    {
        Console.WriteLine("timer elapsed");
        a++;
    }
    public void TimerNotElapsed()
    {
        Console.WriteLine("timer not elapsed");
        a++;
    }
}

样本的预期行为是,在开始时,我们将每秒看到"计时器经过"的消息,在第10秒之后,我们应该只看到"计时器未经过",我们确实看到了,但我们仍然看到"计时器经过"。这意味着AddEventHandler方法可以工作,但是RemoveEventHandler方法不能。

如果你能帮助我,我将非常高兴。

通过反射c#添加和删除事件处理程序

必须将一堆源拼接在一起才能得到我需要的,这是一个一站式扩展方法(如果我们切换组件供应商,可以很容易地修改),以简单地清除我们无法控制的事件上所有现有的事件处理程序。

用法很简单:

thirdPartyControlInstance.ClearEventHandlers(nameof(ThirdPartyControlType.ToolClick));

下面是代码,欢迎提出任何使其更健壮/高效/干净的建议:

public static class EventExtensions
{
    public static void ClearEventHandlers(this object obj, string eventName)
    {
        if (obj == null)
        {
            return;
        }
        var objType = obj.GetType();
        var eventInfo = objType.GetEvent(eventName);
        if (eventInfo == null)
        {
            return;
        }
        var isEventProperty = false;
        var type = objType;
        FieldInfo eventFieldInfo = null;
        while (type != null)
        {
            /* Find events defined as field */
            eventFieldInfo = type.GetField(eventName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (eventFieldInfo != null && (eventFieldInfo.FieldType == typeof(MulticastDelegate) || eventFieldInfo.FieldType.IsSubclassOf(typeof(MulticastDelegate))))
            {
                break;
            }
            /* Find events defined as property { add; remove; } */
            eventFieldInfo = type.GetField("EVENT_" + eventName.ToUpper(), BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);
            if (eventFieldInfo != null)
            {
                isEventProperty = true;
                break;
            }
            type = type.BaseType;
        }
        if (eventFieldInfo == null)
        {
            return;
        }
        if (isEventProperty)
        {
            // Default Events Collection Type
            RemoveHandler<EventHandlerList>(obj, eventFieldInfo);
            // Infragistics Events Collection Type
            RemoveHandler<EventHandlerDictionary>(obj, eventFieldInfo);
            return;
        }
        if (!(eventFieldInfo.GetValue(obj) is Delegate eventDelegate))
        {
            return;
        }
        // Remove Field based event handlers
        foreach (var d in eventDelegate.GetInvocationList())
        {
            eventInfo.RemoveEventHandler(obj, d);
        }
    }
    private static void RemoveHandler<T>(object obj, FieldInfo eventFieldInfo)
    {
        var objType = obj.GetType();
        var eventPropertyValue = eventFieldInfo.GetValue(obj);
        if (eventPropertyValue == null)
        {
            return;
        }
        var propertyInfo = objType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
                                  .FirstOrDefault(p => p.Name == "Events" && p.PropertyType == typeof(T));
        if (propertyInfo == null)
        {
            return;
        }
        var eventList = propertyInfo?.GetValue(obj, null);
        switch (eventList) {
            case null:
                return;
            case EventHandlerDictionary typedEventList:
                typedEventList.RemoveHandler(eventPropertyValue, typedEventList[eventPropertyValue]);
                break;
        }
    }
}

希望这能帮助到一些人!

我认为这是因为你每次都创建一个新的处理程序:(它不匹配以前的处理程序,所以不能从调用列表中删除)

public static void RemoveEventHandler(EventInfo eventInfo,
                    object item, Action action)
{
    var parameters = GetParameters(eventInfo);
    var handler = GetHandler(eventInfo, action, parameters); // <--
    eventInfo.RemoveEventHandler(item, handler);
}

你为什么要包装Action ?失去参数?由于参数的原因,无法添加/删除eventInfo.RemoveEventHandler(item, action);。如果你想删除一个新生成的处理程序,当你想删除它时,你应该返回那个处理程序。

public static Delegate AddEventHandler(EventInfo eventInfo, object item, Action action)
{
    var parameters = GetParameters(eventInfo);
    var handler = GetHandler(eventInfo, action, parameters);
    eventInfo.AddEventHandler(item, handler);
    return handler;
}
public static void RemoveEventHandler(EventInfo eventInfo,
                    object item, Delegate handler)
{
    eventInfo.RemoveEventHandler(item, handler);
}

var handler = EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed);
EventSubscriber.RemoveEventHandler(eventInfo, timer, handler);