我看到三個選項。
選項1.在While循環而不是For Each中逐行讀取。無論如何,如果一切都將處於相同的功能,請使用此功能。
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim line As String = reader.ReadLine()
While line IsNot Nothing
'Contents of your For Each loop go here
line = reader.ReadLine()
End While
選項2:你必須至少的Visual Studio 2012,並希望從這個函數返回的結果,所以你可以使用對於調用該代碼的代碼中的每個循環。
Public Iterator Function GetUrl(ByVal url As String) As IEnumerable(Of String)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim line As String = reader.ReadLine()
While line IsNot Nothing
Yield line
line = reader.ReadLine()
End While
End Function
這樣稱呼它:
For Each line As String In GetUrl("http://example.com")
'...
Next line
方案3:你想從一個函數返回,就像前面的選項,但你不能使用新的迭代器的語言功能。
Public Sub GetUrl(ByVal url As String, ByVal lineAction As Action(Of String))
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim line As String = reader.ReadLine()
While line IsNot Nothing
lineAction(line)
line = reader.ReadLine()
End While
End Sub
這樣稱呼它:
GetUrl("http://example.com", _
Sub(l)
'Do stuff here
End Sub)