I have a number of objects that all share a common base class, I wish to intercept all calls that set Property values and record if these have been set on a per instance basis.
Can I replace the Set Method of a Property at runtime with Reflection?
One approach there is to make the property virtual, and at runtime create a subclass via reflection-emit that override the properties, adding your code. However, this is advanced, and requires you always make sure to create the subclass (so no "new" in code).
However; I wonder if simply implementing INotifyPropertyChanged and handling the event is simpler. The other option is to just build the handling into the regular class in the first place. There are some ways of making this less repetitive, especially if you have a common base-class where you could add a
protected void SetField<T>(ref T field, T value)
{
if(!EqualityComparer<T>.Default.Equals(field,value))
{
field = value;
// extra code here
}
}
With
private int foo;
public int Foo {
get { return foo; }
set { SetField(ref foo, value); }
}
If your base class derives from ContextBoundObject
you can create your objects in a different Context (within the same AppDomain
) and intercept method calls (which is what properties are) and insert your own message sink into the remoting sink chain.
heres one example
http://www.codeproject.com/KB/cs/aspectintercept.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With