我在for-next-statement中创建了3个随机字节。
但是,对于每个for-next,它们总是相同的,例如“333”或“777”。
我想知道为什么会这样,我做错了什么。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = String.Empty
For i As Integer = 0 To 2
s += GetRandomByte().ToString
Next
Me.TextBox1.Text = s
End Sub
Public Function GetRandomByte(Optional ByVal uLow As Byte = 1, Optional ByVal uHigh As Byte = 9) As Byte
Dim r As New Random
Dim b As Integer = r.Next(CInt(uLow), CInt(uHigh + 1))
Return b
End Function
答案 0 :(得分:3)
在新Random的构造函数中,每次都给它一个新的种子。我喜欢使用当前时间戳的哈希码值
New Random(Now.GetHashCode)
答案 1 :(得分:0)
为所有来电保留相同的实例:
Dim r As New Random()
Public Function GetRandomByte(Optional ByVal uLow As Byte = 1, Optional ByVal uHigh As Byte = 9) As Byte
Return r.Next(CInt(uLow), CInt(uHigh + 1))
End Function
或者,向种子传递给种子:
Dim r As New Random(CInt(Date.Now.Ticks And &h0000FFFF))