vb.net 如何在VB函数中添加可选参数/默认值参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/303214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:55:41  来源:igfitidea点击:

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

vb.netparametersoptional-parameters

提问by Steve Duitsman

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

如何在 Visual Basic 中创建一个包含可选参数的方法?

回答by Joel Coehoorn

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

使用Optional关键字并提供默认值。可选参数必须是定义的最后一个参数,以避免创建模棱两可的函数。

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)

回答by Marcelo Nu?ez

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)