开发者

Unsubscribe Lambda Event Handler **With Closure**

I know a lot of people have asked the开发者_StackOverflow中文版 question of "how do I unsubscribe the following"

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

With the obvious answer of

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

But what I'm using a lambda to create a closure? What if my object has an event called AssessmentRationChanged that is of type Action, and I'm wiring it thusly:

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

What if there's a chance I've already set this handler for some / all of the objects in this loop? Is there a way to unsubscribe them?

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


No, you have to store the references to the delegates, basically.

Remember everything that you'll want to unsubscribe later.


You can use the lambda to create a delegate instance that you can use later to unsubscribe:

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

 myObject.MyEvent += a;

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


Since you wrote this:

I'm sure I could use reflection and clear the handler completely

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜