我有2个处理程序使用相同的表单。如何在添加新处理程序(C#)之前删除处理程序?

有帮助吗?

解决方案

如果您在表单中工作,您应该可以执行以下操作:

伪代码:

Delegate[] events = Form1.SomeEvent.GetInvokationList();

foreach (Delegate d in events)
{
     Form1.SomeEvent -= d;
}

从表单外部,您的SOL。

其他提示

如果你知道那些处理程序是什么,只需按照订阅它们的方式删除它们,除了 - =而不是+ =。

如果你不知道处理程序是什么,你就无法删除它们 - 这个想法是事件封装阻止了一个感兴趣的一方在观察事件时破坏了另一个类的兴趣。

编辑:我一直在假设您正在谈论由不同类别实施的事件,例如:一个控件。如果您的班级“拥有”事件,然后只需将相关变量设置为null。

我意识到这个问题相当陈旧,但希望它可以帮助别人。您可以通过一点反思取消注册任何类的所有事件处理程序。

public static void UnregisterAllEvents(object objectWithEvents)
{
    Type theType = objectWithEvents.GetType();

    //Even though the events are public, the FieldInfo associated with them is private
    foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
    {
        //eventInfo will be null if this is a normal field and not an event.
        System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
        if (eventInfo != null)
        {
            MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
            if (multicastDelegate != null)
            {
                foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
                {
                    eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
                }
            }
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top