如何正确使用System.Random类?

时间:2014-05-15 20:27:06

标签: vb.net random

每当我尝试使用Random.Next方法时,它会选择1个随机变量并每次都返回。我试图生成两个随机整数用于此类中的坐标,这样我就可以创建多个Enemy个对象,每个对象都有自己的坐标。

Public Class Enemy
    Dim _name As String
    Public Property name() As String ...

    Dim _start_point() As Integer
    Public Property start_point() As Integer()
        Get
            Return _start_point
        End Get
        Set(ByVal value As Integer())
            _start_point = value
        End Set
    End Property

    Dim _length As Integer
    Public Property length As Integer ... 

    Dim _space_filled(,) As Integer
    Public Property space_filled As Integer(,) ...


    Dim gen_x As New Random()
    Dim gen_y As New Random()


    Public Sub New(ByVal namep As String, ByVal lengthp As Integer)
        name = namep
        length = lengthp

        ReDim _start_point(2)

        GenerateStartPoint()
        Debug.Print(name & " start point: {" & start_point(0) & ", " & start_point(1) & "}")
    End Sub

    Public Sub GenerateStartPoint()
        start_point = {gen_x.Next(0, 10), gen_y.Next(0, 10)}
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

你应该实现一个新的Random()实例,然后在需要一个单独的变量时调用Random()。Next()。由于Random()从CPU时间中获取它的种子,如果你几乎同时实例化它们,它们将从同一种子产生。