How to add an optional parameters/default value parameters in VB function?

拥有回忆 提交于 2019-12-08 14:26:10

问题


How can I create a method that has optional parameters in it in Visual Basic?


回答1:


Use the Optional keyword and supply a default value. Optional parameters must be the last parameters defined, to avoid creating ambiguous functions.

Sub MyMethod(ByVal Param1 As String, Optional ByVal FlagArgument As Boolean = True)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If

End Sub

Call it like this:

MyMethod("test1")

Or like this:

MyMethod("test2", False)



回答2:


Have in mind that optional argument cannot have place before a required argument.

This code will show error:

Sub ErrMethod(Optional ByVal FlagArgument As Boolean = True, ByVal Param1 As String)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If
End Sub

It is common error, no much explained by debugger... It have sense, imagine the call...

ErrMethod(???, Param1)


来源:https://stackoverflow.com/questions/303214/how-to-add-an-optional-parameters-default-value-parameters-in-vb-function

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