2

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

4

3 回答 3

10

如果您正在使用表单本身,您应该能够执行以下操作:

伪代码:

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

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

在表格之外,您的 SOL。

于 2008-11-13T17:55:00.903 回答
7

如果您知道这些处理程序是什么,只需以与您订阅它们相同的方式删除它们,除了使用 -= 而不是 +=。

如果您不知道处理程序是什么,则无法删除它们 - 事件封装的想法是防止感兴趣的一方在观察事件时破坏另一类的利益。

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

于 2008-11-13T17:50:12.363 回答
2

我意识到这个问题已经很老了,但希望它能帮助别人。您可以通过一点反射取消注册任何类的所有事件处理程序。

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);
                }
            }
        }
    }
}
于 2010-08-06T18:59:18.613 回答