I have a delegate, MyDelegate(s as String). I want to send a ParamArray of Pairs to another method that will iterate through the passed array of pairs, invoking each delegate in turn with its paired parameter.
I call the iterator like this
MyMethod(addressOf Method1:Param1,addressOfMethod2:Param2)
The iterator method
MyMethod(ParamArray Calls() as Pair)
tries to do something like this
For each p as Pair in Calls
dim md as MyDelegate
md = p.left
md.Invoke(p.Right)
Next
This compiles, but throws an IllegalCastException. I’ve tried every casting trick I know and also messed with trying to convert to and from Ptr, but no luck.
seems to work ok here
new desktop project
on Window1 I added
OneParamDelegate( param as variant)
added 2 methods to Window1
call1(v as variant)
call2(v as variant)
both have just break statements in them
then I added
Public Sub CallByPairs(ParamArray calls as Pair)
For i As Integer = 0 To calls.ubound
Dim toCall As OneparamDelegate = calls(i).Left
Dim param As Variant = calls(i).Right
toCall.Invoke(param)
Next
End Sub
and all this is then called in one of two ways in the Window1.Open event
CallByPairs( New Pair(AddressOf call1, 123), New Pair(AddressOf call2, "123") )
CallByPairs( AddressOf call1:123, AddressOf call2:"123" )
I think there’s a signature mismatch because my delegates don’t have a parameter, but if I fix that by adding a parameter to the delegate, and simply passing each delegate with its parameter to the iterator instead of passing pairs, the question becomes how to get the passed parameters out of the variants that the delegates are passed in. The compiler will let me cast the variant -
MyDelegate(passedvariant).Invoke
auto-completes, but then the compiler complains that the parameter is missing.
variants dont need to explicitly support delegates for this to work
I was just slow to post while I wrote the code
see above - it works and you can call the delegates passed in by pairs
Weird, I’m doing exactly what you wrote as far as I can see, and still getting an IllegalCastException on the line that Dims ToCall as MyDelegate, using Xojo 2019r3.1.
OK, got it! My target methods didn’t take parameters (I was building up slowly converting some existing code and hadn’t gotten to that yet, lol). Once all the signatures matched it works, thanks!
[quote=486205:@Norman Palardy]variants dont need to explicitly support delegates for this to work
I was just slow to post while I wrote the code
see above - it works and you can call the delegates passed in by pairs[/quote]
Oops, my original post seems to have disappeared, not relevant in any case.