-1

VB.NETで2つのオーバーロードされた関数を記述したいと思います。

2つの関数のロジックのほとんどは同じであるため、2つのオーバーロードに対して関数全体を複製するだけでは不十分です。

これは、オーバーロードされた各関数に、次のようなオプションのパラメーターを使用して別の関数(コアロジックを含む)を呼び出させることで実現できます。

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

言及することが2つあります:

まず、オプションのパラメーターを持つ関数はプライベートですが、固定パラメーターのバージョンはパブリックです。これは大きな違いです

第二に:あなたは必須にして使用することがstateIdでき_GetLocationDetailsます

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

このコードで何を達成しているのかわかりません。2つのパブリック関数を削除して、プライベート関数をパブリックに変更することもできます。

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