如何在 VB.net 中使用函数的参数作为其可选参数的默认值

How to use parameter of a function as default value of its optional paramterer in VB.net

如何使用函数参数的值作为 VB.net 中可选参数的默认值?

这对我不起作用:

Public Function func(ByVal param1 As String, ByVal param2 As String, ByVal Optional param3 As String = param1) As String
   Return ""
End Function

请参阅 documentationOptional 参数了解为什么这不起作用:

  • Every optional parameter in the procedure definition must specify a default value.

  • The default value for an optional parameter must be a constant expression.

  • Every parameter following an optional parameter in the procedure definition must also be optional.

因此,您需要这样的东西才能按预期工作:

Function func(ByVal param1 As String, ByVal param2 As String, ByVal Optional param3 As String = "") As String
    If(String.IsNullOrEmpty(param3) Then
        param3 = param1
    End If

    Return ""
End Function

但是,您可以通过重载而不是 Optional:

来解决此问题
Function func(ByVal param1 As String, ByVal param2 As String) As String
    Return func(param1, param2, param1)
End Function

Function func(ByVal param1 As String, ByVal param2 As String, ByVal param3 as String) As String
    Return ""
End Function    

尽管可能不是最清晰的实现,所以如果您这样做,请务必添加 XML 对方法的注释,以便易于理解用法。