1

好吧,我已经生成了这个随机字符串,但我最近注意到了一个致命的缺陷。当我生成一个随机字符串时,关闭程序并生成另一个随机字符串,它与第一代相同。这是代码:

   Public Function RandomString(ByVal length As Integer) As String
    Dim strb As New System.Text.StringBuilder
    Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} 

    Dim UpperBound As Integer = UBound(chars)

    For x As Integer = 1 To length
        strb.Append(chars(Int(Rnd() * UpperBound)))
    Next

    Return strb.ToString

End Function

Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
    Try
        System.Diagnostics.Process.Start("Link Removed!")
    Catch
    End Try
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim repeatCnt As Integer

    'Check for valid numeric entry
    If Integer.TryParse(TextBox2.Text, repeatCnt) Then
        For repeatIdx As Integer = 1 To repeatCnt
            Dim rndstring As String
            'Generate random string...
            rndstring = RandomString(24)
            '...and append to text box with a line break
            RichTextBox1.Text &= rndstring & vbCrLf
        Next
    Else
        MessageBox.Show("Please enter a valid integer number in the text box")
    End If
End Sub
4

2 回答 2

1

您的问题是您正在运行 Rnd() 而不是使用Random类。

为了避免Rnd()每次都给出相同的“随机”数字序列,应该调用Random.Next() (以便使用机器时钟作为初始值/种子)。

所以在你的情况下:

Dim random As New System.Random()
Public Function RandomString(ByVal length As Integer) As String
   Dim strb As New System.Text.StringBuilder
   Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} 

   Dim UpperBound As Integer = UBound(chars)

   For x As Integer = 1 To length
      strb.Append(chars(Int(random.Next(UpperBound)))
   Next

   Return strb.ToString

End Function     
于 2013-02-03T13:58:27.237 回答
0

尝试生成这样的随机字符串:

Public Shared Function GeneratePass() As String

    Dim unique As Guid = Guid.NewGuid
    Return unique.ToString.Substring(1, 6)

End Function
于 2013-02-03T22:35:26.507 回答