[英]How do I unregister all handlers for a form event?
I have 2 handlers using the same form. 我有2个处理程序使用相同的表单。 How do I remove the handlers before adding the new one (C#)?
如何在添加新处理程序(C#)之前删除处理程序?
If you are working in the form itself, you should be able to do something like: 如果您在表单中工作,您应该可以执行以下操作:
PseudoCode: 伪代码:
Delegate[] events = Form1.SomeEvent.GetInvokationList();
foreach (Delegate d in events)
{
Form1.SomeEvent -= d;
}
From outside of the form, your SOL. 从表单的外部,你的SOL。
If you know what those handlers are, just remove them in the same way that you subscribed to them, except with -= instead of +=. 如果你知道那些处理程序是什么,只需按照订阅它们的方式删除它们,除了 - =而不是+ =。
If you don't know what the handlers are, you can't remove them - the idea being that the event encapsulation prevents one interested party from clobbering the interests of another class in observing an event. 如果你不知道处理程序是什么,你就无法删除它们 - 这个想法是事件封装阻止了一个感兴趣的一方在观察一个事件时破坏了另一个类的兴趣。
EDIT: I've been assuming that you're talking about an event implemented by a different class, eg a control. 编辑:我一直在假设您正在谈论由不同的类实现的事件,例如控件。 If your class "owns" the event, then just set the relevant variable to null.
如果您的类“拥有”该事件,则只需将相关变量设置为null。
I realize this question is rather old, but hopefully it will help someone out. 我意识到这个问题已经很老了,但希望它可以帮助别人。 You can unregister all the event handlers for any class with a little reflection.
您可以通过一点反射取消注册任何类的所有事件处理程序。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.