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

remove lambda expression from PropertyChanged (equivalent of p.PropertyChanged -= (s,a) => { ... })

我有一个 class 实现了 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.

作为@Sweeper 答案的补充,您可以使用事件处理程序方法完成相同的操作,而无需 lambda 表达式的负担:

private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch (e.PropertyName) 
    {
        ...
    }
}

然后您可以使用它来订阅 PropertyChanged 事件:

p.PropertyChanged += OnPropertyChanged;

取消订阅:

p.PropertyChanged -= OnPropertyChanged;

来自 docs 的其他信息:

To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you are handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event.