我写了一个函数,在你读它时告诉你它的函数本身:
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上找不到适用于我的问题的任何内容。
有人可以向我解释为什么我这么笨,我怎么能更好地理解如何处理返回值?
答案 0 :(得分:2)
该函数将返回您的值,但您需要将返回值赋值给变量,然后在Calling方法中使用它,例如:
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
答案 1 :(得分:0)
我不完全确定我理解这个问题,但你的意思是这样吗?
Public Function TestConnect() As Int32
...
Dim errStatus As Int32
...
答案 2 :(得分:0)
Dim returnCode as Int32 = SQLHook.TestConnect()
MessageBox.show(
If(returnCode = 1, "OK", "Error"), "AppName", MessageBoxButtons.OK,
If(returnCode = 1, MessageBoxIcon.Information, MessageBoxIcon.Error)
)