Can you pass a delegate function as an optional parameter?

我怕爱的太早我们不能终老 提交于 2019-12-11 13:42:57

问题


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).



来源:https://stackoverflow.com/questions/31191718/can-you-pass-a-delegate-function-as-an-optional-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!