Rich wrote:
I recently started using delegates in my VB apps to handle asynchronous
operations. Based on the examples that I followed, delegates appear to work
in a similar way as Interfaces. Interfaces define methods and functions
that a class which implements the interface must also contain - so I get the
impression that an Interface is like a skeleton of the methods... And a
delegate defines the arguments for a function which have to be followed/used
by the functions/methods which are called by events assigned to the delegate.
<snip>
The declaration of a delegate defines a method signature and, under the
curtains, defines a new class that inherits from System.Delegate. This
class is capable of storing references to methods, just as if they were
function pointers, as long as the method signature matches the one
specified upon the class declaration.
When you declare a delegate, you're actually specifying the signature
of its Invoke method:
Delegate Function MyDelegate(ByVal SomeValue As Integer) As String
the declaration above is conceptually similar to having a class
declaration like this (only that it's forbidden by the framework to
inherit from System.Delegate: only compilers can do so):
Class MyDelegate
Inherits System.Delegate
Sub New(Source As Object, MethodName As String)
MyBase.New(Source, MethodName)
End Sub
Sub New(Source As Type, MethodName As String)
MyBase.New(Source, MethodName)
End Sub
Function Invoke(ByVal SomeValue As Integer) As String
'well, I'm just guessing, here:
Dim Result As Object = DynamicInvoke(SomeValue)
Return CType(Result, String)
End Function
End Class
Notice that the class constructor asks for the method name, not some
funky method pointer (because there aren't really function pointers
available in the managed environment).
So, when you instanciate a delegate:
Dim S As MyDelegate = AddressOf MyMethod
You're actually doing something like this, where the underlying type
system will locate the actual method named "MyMethod" whose signature
matches the one of the delegate's Invoke method.
Dim S As New MyDelegate(Me, "MyMethod")
Smoke and mirrors, as allways, but really nice mirrors, way cool
smoke... =)
HTH.
Have fun,
Branco.