CallerMemberName in an extension (INotifyPropertyChanged)

依然范特西╮ 提交于 2019-12-02 08:09:15

Simply, it isn't possible. You need 3 pieces of information:

  • the event-handler instance (this.PropertyChanged, on the left)
  • the event-name (propertyName, supplied by the compiler)
  • the sender (sender)

sender cannot be inferred from any of the other information, and there is no compiler option to provide it. However, frankly, I would simply use an instance method instead:

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if(handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

Then the caller simply issues:

OnPropertyChanged(); // job done

You could of course have OnPropertyChanged call your static method, but that seems unnecessary.

In some ways it feels like we should be able to just pass in the INotifyPropertyChanged instance to use for both sender and to access the PropertyChanged, but of course we can't get the actual delegate from an event declaration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!