0

我写了一个函数,当你阅读它时,它会告诉你它的函数本身:

Public Function TestConnect()
    Dim verbinding As MySqlConnection
    Dim errStatus As String

    verbinding = New MySqlConnection()
    verbinding.ConnectionString = "server=" & vardbHost & "; port=" & vardbPort & "; uid=" & vardbUser & "; pwd=" & vardbPass & "; database=" & vardbName & ";"

    Try
        verbinding.Open()
        verbinding.Close()
        errStatus = 0
    Catch myerror As MySqlException
        verbinding.Dispose()
        verbinding.Close()
        errStatus = 1
    End Try

    Return errStatus
End Function

现在我以我的主要形式调用这个函数,我想如果我使用 Try 然后捕获 1 或 0,那么我可以用它做点什么。(例如,显示带有错误消息的表单)但这似乎不起作用,我在 Google 上找不到任何适用于我的问题的内容。

任何人都可以向我解释为什么我如此愚蠢以及如何更好地理解如何处理返回值?

4

3 回答 3

2

该函数将返回您的值,但您需要将该返回值分配给一个变量,然后在您的调用方法中使用它,例如:

Dim errStatus As Integer
errStatus = SQLHook.TestConnect()
If errStatus = 1 Then
    'Show the error form
End If

或者更简单地说,直接测试返回值:

If SQLHook.TestConnect()= 1 Then
    'Show the error form
End If

您还应该真正理清函数中键入的变量:

Public Function TestConnect() as Boolean
    Dim errStatus As Boolean
    Try
        errStatus = True
    Catch myerror As MySqlException
        errStatus = False
    End Try

    Return errStatus  
End Function

或者更简单地说,不要打扰变量:

Public Function TestConnect() as Boolean

    Try
        ...
        Return True
    Catch myerror As MySqlException
        ...
        Return False
    End Try
End Function
于 2013-02-22T11:21:37.327 回答
0

不完全确定我理解这个问题,但你的意思是这样的吗?

Public Function TestConnect() As Int32
  ...
  Dim errStatus As Int32
  ...
于 2013-02-22T11:15:39.153 回答
0
Dim returnCode as Int32 = SQLHook.TestConnect()

MessageBox.show(
         If(returnCode = 1, "OK", "Error"), "AppName", MessageBoxButtons.OK,
         If(returnCode = 1, MessageBoxIcon.Information, MessageBoxIcon.Error)
       ) 
于 2013-02-22T11:26:31.713 回答