您好,我在0和10之间有5个唯一的数字,我正在做以下事情:

Dim RandomClass As New Random()
Dim RandomNumber As Integer
For counter As Integer = 0 To 5
    RandomNumber = RandomClass.Next(0, 10)
    MsgBox(RandomNumber )
Next

有时它可以工作,我得到的数字是:“1、7、4、9、3”
但有时我会得到重复的数字,例如:“5,2,3,2,7”

如何确定每次都有唯一的号码?

谢谢。

最佳答案

使用HashSet(Of Integer)记住已经打印出的数字:

Dim RandomClass As New Random()
Dim RememberSet As New HashSet(Of Integer)

Dim RandomNumber As Integer

While RememberSet.Count < 5
    RandomNumber = RandomClass.Next(0, 10)
    If RememberSet.Add(RandomNumber) Then
        MsgBox(RandomNumber)
    End If
End While

10-08 14:38