有许多不同的方式来处理这一点,根据项目的实际需求。首先,我会问你是否真的需要一个字符串数组作为返回类型。对于大多数情况,数组不如实用的List(Of String)或实现IEnumerable的其他类型。
这里有两个选项,它们都涉及List(Of String)。然而,将列表返回给调用者,然后可以选择使用与数据工作表型的许多有用的方法:
这是这样,我会建议:
Public Function getListOfMotonum() As List(Of String)
Dim SQL As String = "SELECT motonum FROM moto"
Dim output As New List(Of String)()
' Set the connection string in the Solutions Explorer/Properties/Settings object (double-click)
Using cn = New SqlConnection(Properties.Settings.[Default].MyConnectionString)
Using cmd = New SqlCommand(SQL, cn)
cn.Open()
Try
Dim dr = cmd.ExecuteReader()
While dr.Read()
output.Add(dr("motonum").ToString())
End While
Catch e As SqlException
' Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
End Using
End Using
Return output
End Function
这里是其消耗该函数的输出的代码一个简单的例子:
Private Sub PrintListToConsole()
Dim MyMotonumList = Me.getListOfMotonum()
For Each item As String In MyMotonumList
Console.WriteLine(item)
Next
End Sub
如果项目需要一个字符串数组,该方法可能会发生变化。您可以从同样的功能和几个小的改动返回一个字符串:
' Change the return type in the function signature:
Public Function getArrayOfMotonum() As String()
Dim SQL As String = "SELECT motonum FROM moto"
Dim output As New List(Of String)()
' . . . Same Data Access code as above:
' Just use the .ToArray method of the List class HERE:
Return output.ToArray()
End Function
或者,你可以在你的客户端代码中使用同样的方法,消耗它返回一个列表中的原始功能:
Private Sub PrintArrayToConsole()
Dim MyMotonumArray = Me.getArrayOfMotonum()
For Each item As String In MyMotonumArray
Console.WriteLine(item)
Next
End Sub
从你的函数返回列表提供了一个更灵活的返回类型,有许多有用的方法。
作为便笺,请允许我在使用数据访问资源时推荐使用使用块。这会为您处理正确的拆卸和处理Connection和Command对象。