我爲VB.net如何重複後隨機排列索引列表(串),超出範圍
一個新手程序員所以我一直停留在這個代碼,這是隨機名稱生成。
Private Function RandomLname(ByRef ranLname As String) As String
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("[pathto file.txt]", Encoding.Default)
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While reader.Peek <> -1
lines.Add(reader.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
'the error shown in this line
ranLname = lines(line)
Return ranLname
reader.Close()
reader.Dispose()
End Function
我不斷收到ArgumentOutOfRangeException異常幾年運行後,任何人都可以幫助我嗎? 我需要腳本從頭再次讀取列表,當它到達list.count任何人都可以有想法?
任何幫助,將不勝感激。
嘗試'線= rnd.Next(lines.Count)'。 – Enigmativity
你的代碼有一個主要的缺陷,那就是你在'Return'語句之後關閉了文本文件,即你根本沒有關閉它。您應該使用'Using'語句打開它,然後隱式關閉它,而不管該方法如何結束。 – jmcilhinney
我已經刪除了reader.Close()和reader.Dispose(),但它不會重新排列列表。即使當我刪除(+ 1)列表不會產生任何結果60 +結果書面 – Hyuichiro