gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:03:13 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com