如何解决这个问题"函数不会在所有代码路径上返回值"

时间:2017-12-11 11:44:26

标签: vb.net

我正在为我的大学任务做一个简单的ID生成器。但是现在我面临这个问题,它显示"函数不会在所有路径上返回值"。我得到的结果总是" F"路径。我该怎么办?

Private Function GenerateID(ByVal gender As String) As String

    Dim yearJoin As Int32 = Now.Year.ToString().Substring(2, 2)

    If String.Compare(gender, "Male") Then
        Return (yearJoin & "M" & (maxRows + 1).ToString("D3"))
    ElseIf String.Compare(gender, "Female") Then
        Return (yearJoin & "F" & (maxRows + 1).ToString("D3"))
    End If

End Function

2 个答案:

答案 0 :(得分:0)

如果匹配任何条件,只需返回一些默认值,如null:

Private Function GenerateID(ByVal gender As String) As String

    Dim yearJoin As Int32 = Now.Year.ToString().Substring(2, 2)

    If String.Compare(gender, "Male") Then
        Return (yearJoin & "M" & (maxRows + 1).ToString("D3"))
    ElseIf String.Compare(gender, "Female") Then
        Return (yearJoin & "F" & (maxRows + 1).ToString("D3"))
    End If
    Return Nothing
End Function

答案 1 :(得分:0)

方法必须在任何情况下都返回一个值。因此,要么... Else添加If..ElseIf...,要添加最终Return something(作为后备值),要么在提供的gender不是{{1}的情况下抛出异常也不是Male

我更喜欢后者(因为还有什么呢?):

Female

您还应该使用Private Function GenerateID(ByVal gender As String) As String Dim yearJoin As String = Date.Today.Year.ToString().Substring(2, 2) Dim isMale As Boolean = String.Equals(gender, "Male", StringComparison.InvariantCultureIgnoreCase) Dim isFemale As Boolean = String.Equals(gender, "Female", StringComparison.InvariantCultureIgnoreCase) If Not isMale AndAlso Not isFemale Then Throw New ArgumentException($"{NameOf(gender)} must either be Male or Female", NameOf(gender)) End If Dim maleFemaleLetter = If(isMale, "M", "F") maxRows += 1 Dim id As String = $"{yearJoin}{maleFemaleLetter}{(maxRows).ToString("D3")}" Return id End Function Option Strict On返回一个整数。 String.Compare将此静默转换为Option Strict Off。请改用Boolean。与String.Equals相同,返回String.Substring而不是String。编写类型安全的代码以防止令人讨厌的错误。