在函数中有一个可选参数

时间:2014-01-22 17:24:50

标签: vb.net

只是一个非常快速的问题:我想创建一个带有可选参数的函数,因为我无法在函数中找到参数。结果我在visual basic中编写了以下函数:

Sub characterListLength(ByVal Optional)
    Dim rowCount As Integer
    Dim endOfArray As Boolean
    While endOfArray = False
        If dataArray(0, rowCount) And dataArray(1, rowCount) = "" Then
            arrayLength = rowCount
            endOfArray = True
        Else
            rowCount += 1
        End If
    End While



End Sub

但是在第一行:

Sub characterListLength(ByVal Optional)

如果代码中出现标识符,则会出现错误(ByVal可选)。我不知道如何修复此错误并具有可选参数。如果有人能解释我还需要做些什么来解决它,那将非常有用。

4 个答案:

答案 0 :(得分:2)

您需要一个实际变量,例如:

Sub characterListLength(Optional ByVal optionalNumber As Integer = 0)

答案 1 :(得分:2)

如果你说:

  

因为我无法在函数中找到参数

然后使用不带参数的方法:

Sub characterListLength()
    'Here your code
End Sub

答案 2 :(得分:0)

您需要为参数指定名称并切换关键字的顺序

Sub characterListLength(Optional ByVal p = Nothing)

答案 3 :(得分:0)

可选参数的一个更好的“dot-nettier”替代方法是使用重载方法。请考虑以下事项:

Overloads Sub ShowMessage()
    ShowMessage("This is the default alter message")
End Sub

Overloads Sub ShowMessage(ByVal Message As String)
    Console.WriteLine(Message)
End Sub

这样写的你可以两种方式调用上面的方法:

ShowMessage() 'will display default message
ShowMessage("This is custom message") 'will display method from the parameter

演示:http://dotnetfiddle.net/OOi26i

相关问题