I would like to have a function that can "wrap" any other function call. In this particular case, it would allow me to write some more generic transaction handling around some specific operations.
I can write this for any particular number of arguments, e.g. for one argument:
Public Shared Sub WrapFunc(Of T)(ByVal f As Action(Of T), ByVal arg As T)
' Test some stuff, start transaction
f(arg)
' Test some stuff, end transaction
End Sub
... but I was hoping to have this handle any number of arguments without having to have duplicate code for 0 args, 1 arg, 2 args, etc.
Is there a way of doing this?
[Edit] Thanks to Robert Fraser for the c# code. For reference, here's a translation to VB:
[Edit2] Corrected code. Unfortunately, there doesn't seem to be a way around having the separate "ActAsFunc" functions in vb. On the plus side, those are hidden from anyone using the closures and the closures are re-usable.
Public Shared Sub WrapFunc(ByVal f As Action)
_WrapFunc(f)
End Sub
Public Shared Sub WrapFunc(Of T1)(ByVal f As Action(Of T1), ByVal arg1 As T1)
_WrapFunc(Closure(f, arg1))
End Sub
Public Shared Sub WrapFunc(Of T1, T2)(ByVal f As Action(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2)
_WrapFunc(Closure(f, arg1, arg2))
End Sub
Private Shared Sub _WrapFunc(ByVal f As Action)
' Test some stuff, start transaction
f()
' Test some stuff, end transaction
End Sub
Private Shared Function Closure(Of T1)(ByVal f As Action(Of T1), ByVal arg1 As T1) As Action
Return New Action(Function() _ActAsFunc(f, arg1))
End Function
Private Shared Function Closure(Of T1, T2)(ByVal f As Action(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2) As Action
Return New Action(Function() _ActAsFunc(f, arg1, arg2))
End Function
Private Shared Function _ActAsFunc(Of T1)(ByVal f As Action(Of T1), ByVal arg1 As T1) As Object
f(arg1) : Return Nothing
End Function
Private Shared Function _ActAsFunc(Of T1, T2)(ByVal f As Action(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2) As Object
f(arg1, arg2) : Return Nothing
End Function