CallerMemberName in an extension (INotifyPropertyC

2020-05-01 07:04发布

I am currently implementing an Extension for the INotifiyPropertyChanged interface, you can read this:

INotifyPropertyChanged - Event stays null

for furhter information.

Now I would like to extend this extension further so that I dont need to state the MemberExpression and when calling it from inside a set that the CallerMemberName Attribute does the rest.

So I have tried to do the following (based on the links provided in my last stackoverflow question):

public static void Notify(this PropertyChangedEventHandler EventHandler, object sender, 
[CallerMemberName] String propertyName = "")
{
    if (EventHandler != null)
    {
        EventHandler(sender, new PropertyChangedEventArgs(propertyName));
    }
}

This allows me to call the method like this:

this.PropertyChanged.Notify(this); //with CallerMemberName
this.PropertyChanged.Notify(this, "RandomProperty"); 

Now I would like to remove the neccessarity to always write the (this, ..) parameter and just call it like so:

this.PropertyChanged.Notify(); //with CallerMemberName
this.PropertyChanged.Notify("RandomProperty"); 

How is this possible?

1条回答
够拽才男人
2楼-- · 2020-05-01 08:04

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.

查看更多
登录 后发表回答