CJ & Fergus,
The problem is IcedCrow is not using Events, he is using Delegates. A
delegate is a reference to a function. Although Events are implemented in
the terms of a Delegate they are distinct elements.
As far as I can tell AddHandler only works with Events and not with Delegate
variables. (members declared with the Event keyword, not variables declared
with a Delegate type.) I get an error about the delegate variable not being
an Event of the containing class when I attempt to use AddHandler on a
Delegate variable.
I understand he has something like:
Public Delegate Sub MySub()
Public Sub DoWork()
Dim subs As MySub
' magic code to initialize the subs variable
subs.Invoke()
End Sub
Public Sub MyWork()
Debug.WriteLine("working", "MyWork")
End Sub
Public Sub MyWork1()
Debug.WriteLine("working", "MyWork1")
End Sub
Public Sub MyWork2()
Debug.WriteLine("working", "MyWork2")
End Sub
When he uses subs.Invoke in the DoWork sub, he wants all three subs MyWork,
MyWork1, and MyWork2 to be called, the only way I know to do this in VB.NET
is to call Delegate.Combine itself. Something like:
Public Sub DoWork()
Dim subs As MySub = AddressOf MyWork
Dim sub1 As MySub = AddressOf MyWork1
Dim sub2 As MySub = AddressOf MyWork2
subs = DirectCast([Delegate].Combine(subs, sub1), MySub)
subs = DirectCast([Delegate].Combine(subs, sub2), MySub)
subs.Invoke()
End Sub
Normally I use a Delegate variable when I have a single function to call. In
the above I would probably create a helper function to hide the DirectCast
in a function, cleaning it up significantly.
Public Sub DoWork()
Dim subs As MySub
subs = MakeWork(AddressOf MyWork, AddressOf MyWork1)
subs = MakeWork(subs, AddressOf MyWork2)
subs.Invoke()
End Sub
Public Function MakeWork(ByVal a As MySub, ByVal b As MySub) As MySub
Return DirectCast([Delegate].Combine(a, b), MySub)
End Function
Hope this helps
Jay
CJ Taylor said:
See, now I can comment on this one.
Alright when it comes to multicasts like this yes you want to use AddHandler
as everyone has said.
Now after a lot of research, especially yesterday, the AddHandler
keyword
is
simply a reference to EventHandlerList.AddHandler (object, delegate). At
least thats the way I understand it. And EventHandlerList is created at
runtime in most cases it seems. The code for its pretty straight forward
(you can find the source out there) not real complex, but when a
delegate
is
multicast like this, it automatically calls Delegate.Combine.
So just use AddHandler.
=)
CJ
types