Discard Lambda Event Handler ** With Closure **

I know that many people have asked the question “how do I unsubscribe from the following”

myButton.Click += (s, e) => MessageBox.Show("Hello World!");

With obvious answer

EventHandler HelloWorld = delegate { MessageBox.Show("Hello World!"); };
myButton.Click -= HelloWorld;
myButton.Click += HelloWorld;

But what do I use lambda to create a closure? What if my object has an event with a name AssessmentRationChangedthat has a type Action, and I connect it this way:

foreach (MassFMVUpdateDTO dto in CurrentProperties)
   dto.AssessmentRationChanged += () => setCellColorBasedOnAssessmentRatioValue(dto);

What if there is a chance that I already set this handler for some / all objects in this loop? Is there a way to unsubscribe?

I'm sure I can use reflection and completely clear the handler, but is there a cleaner way?

+5
source share
3 answers

, , .

, .

+5

lambda , , :

 Action a = () => setCellColorBasedOnAssessmentRatioValue(dto);

 myObject.MyEvent += a;

 // to unsubscribe:
 myObject.MyEvent -= a;
+4

:

I'm sure I can use reflection and completely clear the handler.

The obvious answer would be to use a simple delegate instead of an event:

foreach (MassFMVUpdateDTO dto in CurrentProperties)
   dto.AssessmentRationChanged = () => setCellColorBasedOnAssessmentRatioValue(dto);
+1
source

All Articles