-1

我想在 VB.NET 中编写两个重载函数。

这两个函数中的大部分逻辑都是相同的,所以我不想只为两个重载复制整个函数。

我可以通过让每个重载函数调用另一个带有可选参数的函数(包含核心逻辑)来实现这一点,如下所示:

Public Overloads Function GetLocationDetails(ByVal countryId As Integer) As LocationInfo
    Return _GetLocationDetails(countryId)
End Function

Public Overloads Function GetLocationDetails(ByVal countryId As Integer, ByVal stateId As Integer) As LocationInfo
    Return _GetLocationDetails(countryId, stateId)
End Function

' This is the function providing the core logic for the two overloaded functions
Private Function _GetLocationDetails(ByVal countryId As Integer, Optional ByVal stateId As Integer = 0) As LocationInfo
    Dim returnVal As New LocationInfo

    Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
        Using cmd As SqlCommand = con.CreateCommand
            cmd.CommandText = "SELECT name, population FROM locations WHERE countryId = @countryId"
            cmd.Parameters.Add(New SqlParameter("@countryId", countryId))

            ' If there is a stateId, this function was called by the overloaded function that has a stateId parameter, so add that to the query
            If stateId <> 0 Then
                cmd.CommandText &= " AND stateId = @stateId"
                cmd.Parameters.Add(New SqlParameter("@stateId", stateId))
            End If

            con.Open()
            Using dr As SqlDataReader = cmd.ExecuteReader
                If dr.Read Then
                    returnVal.Name = dr("name")
                    returnVal.Population = dr("population")
                End If
            End Using
        End Using
    End Using

    Return returnVal
End Function

Public Class LocationInfo
    Public Name As String
    Public Population As Integer
End Class

但是使用可选参数似乎不是很优雅,并且似乎首先否定了重载函数的整个目的。

有没有更好的办法?

4

2 回答 2

0

我看不出你用这段代码完成了什么。您也可以摆脱两个公共功能并将您的私有功能更改为公共:

Public Function _GetLocationDetails(ByVal countryId As Integer, _
                                    Optional ByVal stateId As Integer = 0) _ 
                                    As LocationInfo
于 2013-02-24T20:16:32.007 回答
0

有两点需要说明:

第一:带有可选参数的函数是私有的,而固定参数版本是公共的。这是一个巨大的差异

第二:您可以强制stateId使用_GetLocationDetails

Public Overloads Function GetLocationDetails(ByVal countryId As Integer) As LocationInfo
    Return _GetLocationDetails(countryId,0)
End Function
于 2013-02-24T18:18:36.307 回答