I want to add a generic callback function to all methods of an object. I found this SO question , but in this question I would have to modify every function of the class. I would like to define some beforeFilter method that gets a trigger before every method call. I know that I could use Action delegates , but I do not know how to do this.
UPDATE: As an example, what I want will be something like this
Class MyClass Sub MyCallback 'callback code... End Sub 'Rest of tyhe code End Class
As you can see, it would be ideal to add a simple (or more than one) method to get a trigger before all other methods. Maybe with some base class or interface, I donβt know (why I ask).
Some other option that I think might be useful is to clone an object and define a new class instead of adding code to an existing one. So, in this Class use Object to access the trhough Type methods
Class NewClass Sub AddCallback(Obj As Object, Callback As Action) 'Add the callback here End Sub End Class
I just guess, maybe some of my options are even not viable, so please help me with this.
Closest approach
What I have is this method
Sub RunWithCallback(beforFilter As Action, f As Action) beforeFilter() f() End Sub
(This means a lot of overloading for RunWithCallback to control Sub and functions with Action and Func delegates with different number of parameters) To use this, I would have to run this Sub instead of calling any of the object's methods (passing the ByRef parameter to catch the return value in the functions). Something like that
Public Sub DoNothing() Debug.WriteLine("Callback working!") End Sub Public Sub BeforeFilter() Debug.WriteLine("Testing callback...") End Sub 'To run the above function RunWithCallback(AddressOf BeforeFilter, AddressOf DoNothing)
I think there should be a better solution for this, which will avoid calling the same sub and avoid overloads, a kind of dynamic extension method for a class class