简体   繁体   中英

Is it possible, to evaluate the event of calling a set property?

Let's say, we have an ordinary C# class with one auto get/set property.

public class Entity
{
       public String SomeProperty {get;set;}

}

Is there any event, that is raised and that I can evaluate, when the set method of the SomeProperty is called?

Is something like this possible in any way, maybe reflection?:

Pseudo Code, NO REAL CODE:

Entity e = new Entity();
e.SomeProperty.SetterCalled += OnSetterCalled;

private void OnSetterCalled(Sender propertyinfo)
{
    propertyinfo pi = propertyinfo;
    Console.Write (pi.Name);
}

I know, I could use CallerMember, but then I had to change the auto property.

No, there is no way to do this.

The setter is just this:

_backingVariable = value;

Assignment does not inherently invoke any methods. As it stands, there is no way to raise an event during a property set utilizing an auto-property.

You can change the code at compile time using something like the technique described in: https://stackoverflow.com/a/18002490/1783619

But otherwise, there is no way to do this.

I would recommend looking into:

INotifyPropertyChanged

Here is a great walkthrough:

Implementing INotifyPropertyChanged - does a better way exist?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM