我正在尝试像这样在 vb.net 中生成一个随机代码
Dim r As New Random
Response.Write(r.Next())
但我想生成 6 位数的代码,应该像 thie 一样是字母数字A12RV1
,所有代码都应该是这样的。
我已经尝试过 vb.net 随机类,但我无法按照我的意愿进行操作。每次执行代码时,我都想获取字母数字代码。我如何在 vb.net 中实现这一点?
我正在尝试像这样在 vb.net 中生成一个随机代码
Dim r As New Random
Response.Write(r.Next())
但我想生成 6 位数的代码,应该像 thie 一样是字母数字A12RV1
,所有代码都应该是这样的。
我已经尝试过 vb.net 随机类,但我无法按照我的意愿进行操作。每次执行代码时,我都想获取字母数字代码。我如何在 vb.net 中实现这一点?
尝试这样的事情:
Public Function GetRandomString(ByVal iLength As Integer) As String
Dim sResult As String = ""
Dim rdm As New Random()
For i As Integer = 1 To iLength
sResult &= ChrW(rdm.Next(32, 126))
Next
Return sResult
End Function
或者您可以执行定义有效字符的通用随机字符串:
Public Function GenerateRandomString(ByRef iLength As Integer) As String
Dim rdm As New Random()
Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim sResult As String = ""
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
我认为这将适合您的要求,
Private sub GenerateString()
Dim xCharArray() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
Dim xNoArray() As Char = "0123456789".ToCharArray
Dim xGenerator As System.Random = New System.Random()
Dim xStr As String = String.Empty
While xStr.Length < 6
If xGenerator.Next(0, 2) = 0 Then
xStr &= xCharArray(xGenerator.Next(0, xCharArray.Length))
Else
xStr &= xNoArray(xGenerator.Next(0, xNoArray.Length))
End If
End While
MsgBox(xStr)
End Sub
笔记: Tested With IDE
编辑: Modified according to SYSDRAGON's Comment