Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Anonymous methods

2009-01-26

Delegates can point to both anonymous functions (mostly refered to as anonymous methods) and regular functions. To instantiate a delegate that will point at a regular function, just use the AddressOf operator followed by the function you want to use the delegate for. This could be the delegate declaration:

Public Delegate Function MyDelegateType(ByVal T1 As Integer, ByVal T2 As Integer) As Integer

Imagine a function that adds two numbers. This could be the code that instantiates the delegate:

Dim X As New MyDelegateType(AddressOf Me.Sum)

And not, when the Invoke method of X is called, the Sum method gets executed.

The delegate knows what to do because a reference to a function is passed to it when it is created. The AddressOf operator is used for that. You could pass some Visual Basic code to the constructor instead of a reference to a function. To do this, use the Function keyword instead. Imagine a delegate declaration called DelegateNoParameters, that takes no parameters, and has no return value. This is how I can instantiate it, passing a function created on the fly to the constructor:

Dim X As New DelegateNoParameters(Function() MessageBox.Show(“Hello!”))

Now, whenever you call the Invoke method of X, a message box will be shown.

To take this one step further, this is how I could use an anonymous function with the delegate declaration that required two parameters and one return value (MyDelegateType):

Dim X As New MyDelegateType(Function(A As Integer, B As Integer) A + B)

Note that the keyword Return isn’t used. Also note that currently, anonymous functions can only contain one single statement in Visual Basic. That of course means lots of limitations, but this feature opens up some possibilities that otherwise would have been unavailable, like Lambda.

Categories: Visual Basic 9

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips