Given any delegate type, one may fairly easily write a class which will combine delegates which are of either that type or a derived type and yield a combined delegate which will do just about everything a MulticastDelegate
can do, and a number of things it can't. The only thing that style of combined delegate would not be able to do is have its subcomponents taken out by Delegate.Remove
(since that function would just regard the combined delegate as a unit). Unlike MulticastDelegate, the combined delegate would be able to include derived delegate types, and would work just fine in places that only want one target.
In vb.net, the code would be something like:
Class DoubleAction(Of T)
Private _Act1, _Act2 As Action(Of T)
Private Sub New(ByVal Act1 As Action(Of T), ByVal Act2 As Action(Of T))
_Act1 = Act1
_Act2 = Act2
End Sub
Private Sub Invoke(ByVal Param As T)
_Act1(Param)
_Act2(Param)
End Sub
Function Combine(ByVal Act1 As Action(Of T), ByVal Act2 As Action(Of T)) As Action(Of T)
Dim newAct As New DoubleAction(Of T)(Act1, Act2)
Return AddressOf newAct.Invoke
End Function
End Class
Translation to C# should be straightforward.
The only real problem with this approach for combining delegates is that boilerplate code is required for every generic family of delegate to be supported (since .net does not allow delegates to be used as generic type parameters).
BeginInvoke
on aMulticastDelegate
. – Pt