كيف يمكنني إلغاء تسجيل جميع معالجات لحدث شكل؟
سؤال
ولقد 2 معالجات باستخدام نفس النموذج. كيف يمكنني إزالة معالجات قبل إضافة واحدة جديدة (C #)؟
المحلول
إذا كنت تعمل في النموذج نفسه، يجب أن تكون قادرة على فعل شيء مثل:
وشبة الكود:
Delegate[] events = Form1.SomeEvent.GetInvokationList();
foreach (Delegate d in events)
{
Form1.SomeEvent -= d;
}
ومن خارج النموذج، SOL الخاص بك.
نصائح أخرى
إذا كنت تعرف ما هي تلك معالجات، فقط إزالتها في بنفس الطريقة التي كنت قد اشتركت لهم، إلا مع - = بدلا من + =
إذا كنت لا تعرف ما هي معالجات، لا يمكن إزالتها - والفكرة هي أن التغليف الحدث يمنع طرف معني واحد من clobbering مصالح فئة أخرى في مراقبة هذا الحدث
تحرير: لقد تم افتراض أن كنت تتحدث عن حدث تنفذها فئة مختلفة، على سبيل المثال عنصر تحكم. إذا صفك "تمتلك" هذا الحدث، ثم عادل تعيين متغير ذات الصلة فارغة.
وأنا أدرك هذا السؤال قديمة نوعا ما، ولكن نأمل أنها سوف تساعد شخص ما. يمكنك إلغاء تسجيل جميع معالجات الأحداث عن أي فئة مع قليل من التفكير.
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);
}
}
}
}
}