c# - 从 PropertyChanged 中删除 lambda 表达式(相当于 p.PropertyChanged -= (s,a) => { ... })

标签 c# propertychanged

我有一个实现 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/

相关文章:

c# - WPF - 更改对象属性时通知 ViewModel

c# - WPF应用程序在并发环境中被PropertyChangedEventManager挂起

WPF 过多的 PropertyChanged 事件

c# - 为 PDF 渲染和分析应用程序选择跨平台库(最好使用 C#)

C# Winforms,没有使用 GrowAndShrink 调整大小的箭头

android - Xamarin TimePicker propertychanged 事件在加载时触发

swift - 有没有办法让 didSet 在更改类中的属性时工作?

c# - Partcover 和 Typemock 集成

c# - 有没有机会,我们可以想象在一个进程(可能是 c#)中什么都进入了堆栈,什么都进入了堆?

c# - "Build"构建我的项目,"Build Solution"没有