フォームイベントのすべてのハンドラーの登録を解除するにはどうすればよいですか?
質問
同じフォームを使用する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);
}
}
}
}
}
所属していません StackOverflow