我有一段代码可以生成随机字符。问题是,每隔一段时间,它就会返回一个错误:
“startIndex cannot be greater than length of string. Parameter name: startIndex”
如何防止发生这种错误?
这是我的代码:
Friend Function gentCtrlChar()
Dim ran As New Random
Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim alpha2 As String = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
Dim rdm As New Random
Dim genChar As String = ""
For i As Integer = 1 To 52
Dim selChar As Integer = rdm.Next(1, 28)
Dim selChar2 As Integer = rdm.Next(1, 28)
genChar = genChar + "" + alpha.Substring(selChar, 1) + "" + alpha2.Substring(selChar2, 1)
On Error Resume Next
Exit For
Next
Return genChar
End Function
如您所见,我尝试放置“On Error Resume Next”,希望以某种方式为我解决错误。但可悲的是,它没有做它的工作。还是我以错误的方式或错误的情况使用它?
有什么帮助吗?
谢谢!