我有一个实现 PropertyChanged 的类。我做了类似的事情来订阅它:
p.PropertyChanged += (s, a) => {
switch ( a.PropertyName) {
...
}
}
我以后如何从 p.PropertyChanged
取消订阅上述代码?等效于(显然不起作用):
p.PropertyChanged -= (s, a) => {
switch ( a.PropertyName) {
...
}
}
最佳答案
你必须把它放在一个变量中:
PropertyChangedEventHandler eventHandler = (s, a) => {
...
};
// ...
// subscribe
p.PropertyChanged += eventHandler;
// unsubscribe
p.PropertyChanged -= eventHandler;
来自 docs :It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event. In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.
关于c# - 从 PropertyChanged 中删除 lambda 表达式(相当于 p.PropertyChanged -= (s,a) => { ... }),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64276621/