我想在 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
但是使用可选参数似乎不是很优雅,并且似乎首先否定了重载函数的整个目的。
有没有更好的办法?