我为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