我收到错误
函数“Login”不会在所有代码路径上返回值。你错过了“退货”声明吗?
我在某种程度上理解了在Stack Overflow上查看各种问题。我的困惑是我有所有代码路径的返回值 - 不是吗?
Public Function Login(Username As String, Password As Integer) As Integer
Dim tableAdapter As New AcquisitionPortalDataSetTableAdapters.ITVF_LoginLogoutTableAdapter
Dim dt As DataTable = tableAdapter.GetData(Username, Convert.ToInt32(Password))
Try
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
For Each dr In dt.Rows
If dr("LAN").ToString = Username AndAlso Convert.ToInt32(dr("Code")) = Password Then
GlobalVariables.iUserType = Convert.ToInt32(dr("Code"))
GlobalVariables.iUserID = Convert.ToInt32(dr("ID"))
Return 1
Else
Return 0
End If
Next
Else
Return 0
End If
Catch
Return 0
End Try
End Function
我已经多次这样做了,据我所知,每个陈述都可以进行评估。任何人都可以提出其他建议,如果可能的话,最好有简短的解释,所以我对未来有所了解吗?
答案 0 :(得分:5)
这是因为编译器不知道您正在检查表是否有行,因此假设您的代码路径可能不会输入For Each
循环。事实上,确实没有必要首先检查行数,因为如果For Each
循环中没有行,它将具有零迭代。
要修正警告,您需要明确地涵盖这种可能性:
Public Function Login(Username As String, Password As Integer) As Integer
Dim tableAdapter As New AcquisitionPortalDataSetTableAdapters.ITVF_LoginLogoutTableAdapter
Dim dt As DataTable = tableAdapter.GetData(Username, Convert.ToInt32(Password))
Try
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
For Each dr In dt.Rows
If dr("LAN").ToString = Username AndAlso Convert.ToInt32(dr("Code")) = Password Then
GlobalVariables.iUserType = Convert.ToInt32(dr("Code"))
GlobalVariables.iUserID = Convert.ToInt32(dr("ID"))
Return 1
Else
Return 0
End If
Next
Return 0 'return here when there are no rows in the datatable
Else
Return 0
End If
Catch
Return 0
End Try
End Function
如果您的用户名是唯一的,那么说您的功能可以更简单(更快),因为如果您找到了用户名,则不必再检查:
Public Function Login(Username As String, Password As Integer) As Integer
Dim tableAdapter As New AcquisitionPortalDataSetTableAdapters.ITVF_LoginLogoutTableAdapter
Dim dt As DataTable = tableAdapter.GetData(Username, Convert.ToInt32(Password))
If dt Is Nothing Then Return 0
For Each dr As DataRow In dt.Rows
If dr.Field(Of String)("LAN") = Username Then
'we found the username now check the password
Return If(dr.Field(Of Int32)("Code") = Password, 1, 0)
End If
Next
'we didn't find a matching username
Return 0
End Function
答案 1 :(得分:-1)
你不能在End Try
之后放一个return语句吗?并在保存结果的函数的开头创建一个变量?在函数结束时,只返回该结果。
我不熟悉VB.NET,但这应该可以解决问题。