Unsubscribe Lambda Event Handler **With Closure**
I know a lot of people have asked the 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.
您可以使用lambda创建一个委托实例,稍后您可以使用它来取消订阅:
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);
链接地址: http://www.djcxy.com/p/51472.html
上一篇: 一个事件处理程序可以不经反射就自引