2014-03-24 60 views
2

我在for-next-statement中創建3個隨機字節。For-Next-Statement中的新隨機數重複相同的值

但是,它們對於每個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 

回答

3

在你的構造新的隨機,給它一個新的種子每一次。我喜歡使用當前時間戳的哈希碼值

New Random(Now.GetHashCode) 
+2

更好的辦法是在方法外部聲明Random實例。 –

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))