OK, I’ve tried but I just don’t get it.
I have two classes logger and class1.
I have a method called logger.Write(string) and method called class1.Execute().
Now in my application I want to have logger.Write(class1.ToString()) run when class1.Execute() is called.
I presume you need to add delegates and events, but I just can’t get my head around this, been scratching it for a couple hours.
One thing, is that the logger and the class are in different namespaces and I don’t want to update the class code for either of them if possible.
Well you certainly can’t do it without changing code in either class (assuming you also don’t want to change everywhere that calls
class1.Execute) – at least not without some deep code-weaving/instrumentation magic. However, you can fairly easily add an event inClass1:The
delegate{}bit is just to make sure that there’s always at least a no-op event handler registered – it means you don’t need to check for nullity.You’d then hook it up by writing:
(This is assuming you’re using C# 3 so you have lambda expressions available to you – let me know if that’s not the case.)
If
Class1implements an interface (sayIFoo), you might want to write an implementation of the interface which wraps another implementation, and just logs before each call:Then just use that wrapper around a “real” implementation wherever you currently just use the implementation.