Can you pass a delegate function as an optional pa

2019-07-29 01:03发布

问题:

I know that in Visual Basic, delegate function cannot contain optional parameters. But can a method take a delegate as an optional parameter?

What I want to do is this:

Delegate Sub MyDelegate(ByVal input As String)


Sub MyDelegateDefault(ByVal input As String)
    'by default do nothing'
End Sub


Sub MyDelegateCustom1(ByVal input As String)
    'do something here'
End Sub

In a different part of code:

Sub OtherFunction(ByVal str As String, Optional ByVal delegate As MyDelegate = AddressOf MyDelegateDefault)
    delegate(str)
End Sub

Sub ParentFunction()
    OtherFunction("", ) '< "" as string, nothing for optional delegate parameter'
End Sub

Note how the final function OtherFunction takes a optional delegate as second parameter.

Is this a thing? Can a delegate function be an optional parameter?

回答1:

A parameter that is of a reference type can only be defaulted to null. Change the default value to null, check for the null condition, and don't call the delegate (do nothing).