我看到三个选项。
选项 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 并希望从此函数返回结果,以便可以在调用此代码的代码中使用 For Each 循环。
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)