How can I create a method that has optional parameters in it in Visual Basic?
如何在Visual Basic中创建一个包含可选参数的方法?
2 个解决方案
#1
63
Just 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
0
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)
#1
63
Just 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
0
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)