你好,我正在尝试在vb.net中创建一个函数来创建一个随机生成的颜色来突出显示表单上ListView中的行。代码的输入是SlaveID,它是一个字节。我遇到的问题是,如果我多次输入相同的SlaveID,我将总是得到相同的颜色输出。由于Rnd采用当前时间来使数字更随机,所以每次我调用此函数时,颜色输出都会发生变化,即使我的输入值保持不变。有没有一个不受时间影响的随机数生成器,可以很容易地替代Rnd?
Private Function GetColourForRow(ByVal SlaveID As Byte)
Dim ListViewItemColour As New ListViewItem
Dim upperbound As Byte = 255
Dim lowerbound As Byte = 100
Dim ColourA As Int16 = CInt(Math.Floor((upperbound * 2 - lowerbound + 1) * Rnd(SlaveID) + 2)) + lowerbound
Dim ColourR As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID))) + lowerbound
Dim ColourG As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID + 5))) + lowerbound
Dim ColourB As Int16 = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd(SlaveID + 15))) + lowerbound
Return ListViewItemColour.BackColorEnd函数
发布于 2016-09-09 14:49:49
由于您使用的是Visual Basic而不是旧的Visual Basic,因此我建议您使用.NET的随机类(https://msdn.microsoft.com/en-us/library/system.random(v=vs.110%29.aspx)。让我们使用OOP,因为它是存在的.
所以这会给你
Public Class MyClass
'We will instanciate the Random number generator using a seed
Private _seed As Integer = CInt(Date.Now.Ticks And &h0000FFFF)
Private Function GetColourForRow(ByVal SlaveID As Byte)
Dim Random As New Random(_seed)
'These numbers will always be the same, because the seed will not change...
Dim number1 = Random.Next(minimum, maximum)
Dim number2 = Random.Next(minimum, maximum)
'Rest of your function
End Function
'Rest of your class
End Class发布于 2016-09-09 07:35:17
要每次生成相同的伪随机数,您可以使用相同的种子进行Randomize:
Private Function GetColourForRow(ByVal SlaveID As Byte)
Static seed# = Rnd() ' Static values will be set only the first time the function is called and will stay the same
Randomize(seed)
' the rest of the code发布于 2016-09-09 07:29:11
在使用Rnd之前,您可以使用一致的x值调用Randomize(x),以便为随机数生成器提供当前时间以外的内容。您可能希望在GetColourForRow的顶部执行此操作。
有关详细信息,请参阅:
https://msdn.microsoft.com/en-us/library/8zedbtdt(v=vs.90).aspx(https://msdn.microsoft.com/en-us/library/8zedbtdt(v=vs.90%29.aspx)
但是,如果在程序中的其他地方使用随机数,这可能会产生无意的副作用。使用诸如MD5或SHA之类的散列函数来一致地将SlaveID映射到一些随机字节可能更合适。
https://stackoverflow.com/questions/39401400
复制相似问题