【发布时间】:2013-12-11 13:13:01
【问题描述】:
我的问题最初是删除一个匿名代表。我查看了找到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);
}
}
【问题讨论】: