简体   繁体   中英

Using reflection to insert code in a property set method .Net

I don't know if this is possible. I am trying to run a piece of custom code upon a property being set, I am trying to do this at runtime using reflection. I cannot work out a way of running a piece of custom code when a value is set.

I can get a reference to the set MethodInfo but I don't know if this is the correct approach.

As I say im not even sure if this is possible.

  PropertyInfo[] pInfos = this.GetType().GetProperties();

  MethodInfo mInfo = pInfos[0].GetSetMethod();

What I am trying to do is have a base object which can attach a property change event to every property that has a custom attribute. Without manually setting the setter method on every class that implements the the base object. The event would then fire a property changed when a property value is set.

It sounds as though you would be best to wrap the target class using the Decorator pattern. Assuming the class you want to wrap is a 3rd party class that you don't have the source code for. You could then wrap the setters that you're interested in and raise an event on your wrapping class when the property is set.

You could maybe look at PostSharp which uses the concept of AOP and could implement this functionality for you automatically at compile time. Warning: Although this may solve your problems today, it may cause headaches for future maintenance, when developers may find things happening as if by magic.

There's also an interface in WPF called INotifyPropertyChanged that might be helpful. It's the same pattern I mentioned earlier and allows you to raise an event when the property is changed. Plus this gives you the opportunity to fire the event only when the value is changed and not every time the setter is called.

Personally I prefer any solution that requires explicit code (ie the INotifyPropertyChanged solution). Although it's repeating code that will be in every setter, the intention is explicit and when you come across the exception to the rule (where you don't want an event to be triggered), you aren't having to come up with a complex mechanism to work around your catch-all solution.

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