다른 방법의 수는 프로젝트의 실제 요구에 따라이 접근 할 수 있습니다. 무엇보다 먼저 반환 유형으로 문자열 배열이 필요한지 물어볼 것입니다. 대부분의 경우 배열은 IEnumerable을 구현하는 List (Of String) 또는 다른 형식보다 덜 유용합니다.
여기에는 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
경우, 접근 방식은 다를 수 :이 기능의 출력을 소비 코드의 사소한 예입니다.
Private Sub PrintArrayToConsole()
Dim MyMotonumArray = Me.getArrayOfMotonum()
For Each item As String In MyMotonumArray
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
을 또는 : 당신은 몇 약간의 수정과 같은 함수에서 문자열을 반환 할 수 있습니다
함수에서 List를 반환하면 많은 유용한 메서드가있는보다 유연한 반환 형식이 제공됩니다.
부수적으로 데이터 액세스 리소스를 사용할 때 Using 블록을 사용하도록 권장합니다. 이렇게하면 Connection 객체와 Command 객체를 올바르게 분리하고 처리 할 수 있습니다.