I’m having difficulty trying to sum up my question in form of a google query (maybe my foo is off):
I’m attempting to give an interface or class some functionality by not editing the type definition itself, but rather by dressing up the object with an interface. The simple example I’m attempting is to attach a Attribute, called [Notify] which has a property change event defined to, ideally, give the interface/class use of the event. I’ve been unsuccessful with this so I’m opening up to any device possible (if any) to achieve the equivalent:
[Notify]
public interface IPerson
{
string Name { get; set; }
}
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public class Notify: Attribute
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Using an IPerson:
IPerson person = PersonFactory.create();
person.PropertyChanged += SomeDelegateHere // the center peice
Of course if you copied this code, person won’t have PropertyChanged. With or without attributes, is there a way to accomplish given the IPerson more functionality without changing the definition (i.e not adding an interface or base class). I get that attributes are changing too, but I’m comfortable with the meta data approach.
Thanks in advance for any light that can be shed.
What you are looking is hooking on such events as method invocations and attaching some actions to that events. This is not default feature of C#, but it can be done via such AOP framework as PostSharp. PostSharp adds this functionality by changing code during build time (it does not use Reflection).
Here is what you need to implement with PostSharp:
Implementation details you can find here.
Usage is very simple:
Keep in mind, that actual code will be injected into assembly during compilation. Attributes cannot add any functionality. They are just meta data. In this case meta data used by PostSharp to generate code and inject it into assembly.