如何在VB.NET中编写重载函数,这些函数都将使用相同的核心代码?

时间:2013-02-24 18:14:18

标签: vb.net overloading

我想在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

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

有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

有两件事需要提及:

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

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

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

答案 1 :(得分:0)

我不知道您使用此代码完成了什么。你也可以摆脱两个公共职能并将你的私人职能改为公共:

Public Function _GetLocationDetails(ByVal countryId As Integer, _
                                    Optional ByVal stateId As Integer = 0) _ 
                                    As LocationInfo