同じフォームを使用するハンドラーが 2 つあります。新しいハンドラーを追加する前にハンドラーを削除するにはどうすればよいですか (C#)?
4917 次
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 に答える