2013-12-11 88 views
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); 
    } 
} 

回答

3

因爲你使用一個變量初始化的實例字段位置:

protected PropertyChangedEventHandler hookup= (sender, arg) => this.OnPropertyChanged(arg.PropertyName); 

但你不能做那。

C# specification

10.5.5.2 10.5.5.2實例字段初始化
...
正在創建的實例字段不能引用該實例變量初始值。因此,在變量初始值設定項中引用this是編譯時錯誤,因爲變量初始值設定項通過簡單名稱引用任何實例成員是編譯時錯誤。


但是,您可以在構造函數初始化hookup

public abstract class Notifiable : INotifyPropertyChanged 
{ 
    protected PropertyChangedEventHandler hookup; 

    public Notifiable() 
    { 
     hookup = (sender, arg) => OnPropertyChanged(arg.PropertyName); 
    } 

    ... 
} 
+0

究竟發生了什麼躲避我。謝謝。 –

相關問題