我的内容与以下内容类似:
public class MyClass
{
private List<MyOjectMapping> mappings;
public void Start()
{
foreach (var mapping in mappings)
{
mapping.ObjectA.PropertyA.PropertyChanged += (s, e) =>
{
// do something with mapping.ObjectB
};
}
}
public void Stop()
{
// unhook events
}
}
public class MyObject : INotifyPropertyChanged
{
public object PropertyA;
public object PropertyB;
}
public class MyOjectMapping
{
public object SomeSortOfKey;
public MyObject ObjectA;
public MyObject ObjectB;
}
正如您所看到的,我正在尝试对lambda事件处理程序中的foreach迭代器执行某些操作。这样做,但这样做,我无法弄清楚如何解开Stop()方法中的事件。
我应该如何处理PropertyChanged事件以便以后取消挂钩并仍然可以访问foreach迭代器?
由于
答案 0 :(得分:3)
如果您想使用多个匿名事件处理程序并且以后仍然可以将它们分离,您只需将分离操作存储在单独的列表中,类似于:
// these actions should be invoked during cleanup
private readonly List<Action> _cleanupActions = new List<Action>();
public void Start()
{
foreach (var m in mappings)
{
// you need both closures in order to reference them inside
// the cleanup action
var mapping = m;
PropertyChangedEventHandler handler = (s, e) => { /* ... */ };
// attach now
mapping.PropertyChanged += handler;
// add a cleanup action to detach later
_cleanupActions.Add(() => mapping.PropertyChanged -= handler);
}
public void Stop()
{
// invoke all cleanup actions
foreach (var action in _cleanupActions)
action();
}
这很简洁,因为它允许任意复杂的清理操作,并且它捕获正确的对象对及其事件处理程序。