I want to add a common callback function to all the methods of an object. I found this SO question but in that aproach, I would have to modify every function of the class. I would like to define some beforeFilter
method that get trigered before every method call. I know I could use Action delegates
for that but I don't know how.
UPDATE: As an example, what I want would be something like this
Class MyClass
Sub MyCallback
'callback code...
End Sub
'Rest of tyhe code
End Class
As you can see, the ideal would be to add a simple (or more than one) method to get trigered before all the rest of the methods. Maybe with some base class or an interface, I don't know (that's why I ask for).
Some other option that I think it might be posible is to clone the object and define a new class instead to add code to the existing one. So in that Class
use the Object
to get access to the methods trhough the Type
Class NewClass
Sub AddCallback(Obj As Object, Callback As Action)
'Add the callback here
End Sub
End Class
I'm just guessing, maybe some of my option are even unviable, so please help my on this
Closest approach
What I have for now, is this method
Sub RunWithCallback(beforFilter As Action, f As Action)
beforeFilter()
f()
End Sub
(This means a lot of overloads for the RunWithCallback
to manage Sub's and Functions with Action
s and Func
s delegates, with different number of parameters) To use this, I would have to run this Sub instead of calling any of the Object methods (passing ByRef
parameter to catch returning value in functions). Something like this
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 to this, something that allow to avoid calling the same sub, and avoid the overloads, some kind of dynamic extension method for the object Class