1
我的問題最初是要刪除一個匿名委託。我看過發現的答案鏈here。不過,我的問題有點不同。由於某種原因,Hookup方法編譯。但變量處理程序不。我得到的錯誤是「this」在上下文中無效......但爲什麼?爲什麼一個方法簽名編譯,但另一個沒有?我可以在這裏實現lambda格式嗎?我真的很想獲得lambda格式,因爲我相信即使它是一個變量它也更具可讀性。但我真的很好奇,但迄今爲止,答案並沒有解決。這在上下文中無效
protected void Hookup(object sender, PropertyChangedEventArgs args)
{
this.OnPropertyChanged(args.PropertyName);
}
protected PropertyChangedEventHandler hookup= (sender, arg) => this.OnPropertyChanged(arg.PropertyName);
完整的代碼是在這裏:
public abstract class Notifiable : INotifyPropertyChanged
{
protected void Hookup(object sender, PropertyChangedEventArgs args)
{
this.OnPropertyChanged(args.PropertyName);
}
protected PropertyChangedEventHandler hookup = (sender, arg) => this.OnPropertyChanged(arg.PropertyName);
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged == null) return;
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
protected void OnObservableChanges(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (var item in e.NewItems)
(item as INotifyPropertyChanged).PropertyChanged += this.Hookup;//(osender, arg) => this.OnPropertyChanged(arg.PropertyName);
if (e.OldItems != null)
foreach (var item in e.OldItems)
//This is the real reason for my problem. I need to be able to unhook the commented out anonymous call.
//As you can see, the lambda format is much easier to read and get the gist of what's up.
(item as INotifyPropertyChanged).PropertyChanged -= this.Hookup;//(osender, arg) => this.OnPropertyChanged(arg.PropertyName);
}
}
究竟發生了什麼躲避我。謝謝。 –