随机数/字母生成器无法正常工作

时间:2015-11-20 18:32:26

标签: vb.net random

大家好我想弄清楚为什么我的代码下面只为所有4/5/8变量生成相同的随机字母/数字:

Public Function GenerateRandomString(ByRef iLength As Integer, Optional numberOnly As Boolean = False) As String
    If numberOnly Then
        Dim RandomClass As New Random()
        Dim RememberSet As New HashSet(Of Integer)
        Dim RandomNumber As Integer

        While RememberSet.Count < 3
            RandomNumber = RandomClass.Next(1, 3)

            If RememberSet.Add(RandomNumber) Then
                Return RandomNumber
            End If
        End While
    Else
        Dim rdm As New Random()
        Dim sResult As String = ""
        Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()

        For i As Integer = 0 To iLength - 1
            sResult += allowChrs(rdm.Next(0, allowChrs.Length))
        Next

        Return sResult
    End If
End Function

这是我用来测试它的代码:

Private Sub testing()
   Dim fourValue1 As String = Nothing
   Dim fourValue2 As String = Nothing
   Dim fourValue3 As String = Nothing
   Dim twelveValue As String = Nothing
   Dim eightValue As String = Nothing

   fourValue1 = GenerateRandomString(4)
   fourValue2 = GenerateRandomString(4)
   fourValue3 = GenerateRandomString(4)
   twelveValue = GenerateRandomString(12)
   eightValue = GenerateRandomString(8)

   debug.print(fourValue1)
   debug.print(fourValue2)
   debug.print(fourValue3)
   debug.print(twelveValue)
   debug.print(eightValue)
End Sub

这就是我获得上述代码输出的内容:

Z4Gb
Z4Gb
Z4Gb
Z4Gb5Sq28VOr
Z4Gb5Sq2

所以你看到 Z4Gb 在每个随机生成的变量中,然后 Z4Gb5Sq2 8 12 < / strong>变量。

那么我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题是每个new Random()调用都获得相同的种子。在类构造函数中创建Random对象。