Someta supports event interceptors. What this means is that when you decorate your event with an implementation of one or both of IEventAddInterceptor
and IEventRemoveInterceptor
you can have your own code called instead. Both event adds and removes allow you to call the original implementation via a provided delegate.
This interface has one method:
void AddEventHandler(EventInfo eventInfo, object instance, Delegate handler, Action<Delegate> proceed);
As you can see, your implementation is provided with everything you need to customize the behavior of the add accessor. If you don't want to call the original add, simply don't invoke proceed
.
public void PropertyGetExample()
{
var testClass = new PropertyGetTestClass();
testClass.Value = 3;
Console.WriteLine(testClass.Value); // Prints 6
}
class PropertyGetTestClass
{
[PropertyGetInterceptor]
public int Value { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
class PropertyGetInterceptor : Attribute, IPropertyGetInterceptor
{
public object GetPropertyValue(PropertyInfo propertyInfo, object instance, Func<object> getter)
{
var currentValue = (int)getter();
return currentValue * 2;
}
}
This interface has one method:
void RemoveEventHandler(EventInfo eventInfo, object instance, Delegate handler, Action<Delegate> proceed);
As you can see, your implementation is provided with everything you need to customize the behavior of the remove accessor. If you don't want to call the original remove, simply don't invoke proceed
.
public void PropertySetExample()
{
var testClass = new PropertySetTestClass();
testClass.Value = 2;
Console.WriteLine(testClass.Value); // Prints 4
}
class PropertySetTestClass
{
[PropertySetInterceptor]
public int Value { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
class PropertySetInterceptor : Attribute, IPropertySetInterceptor
{
public void SetPropertyValue(PropertyInfo propertyInfo, object instance, object oldValue, object newValue, Action<object> setter)
{
var value = (int)newValue;
value *= 2;
setter(value);
}
}