【C#】Random类中构造方法、时间种子与随机数序列的关系

时间:2023-03-09 22:52:40
【C#】Random类中构造方法、时间种子与随机数序列的关系

Random类

构造函数

1) Random random = new Random(); // 无参数构造函数使用系统时钟生成其种子值

然而,系统时钟取值范围有限,因此在小规模计算中,可能无法使用不同的种子值分别调用此构造函数, 这将导致两个random对象生成相同的随机数字序列。

 using System;
using System.Collections.Generic; namespace FirstTest
{
class Program
{
static void Main(string[] args)
{
Random random1 = new Random();
List<int> list1 = new List<int>();
GetRandomNumbers(random1, list1);
Console.WriteLine("random1对象使用默认构造函数生成的随机数序列: ");
PrintList(list1); Random random2 = new Random();
List<int> list2 = new List<int>();
GetRandomNumbers(random2, list2);
Console.WriteLine("random2对象使用默认构造函数生成的随机数序列: ");
PrintList(list2);
} private static void GetRandomNumbers(Random rand, List<int> list)
{
for (int i = ; i <= ; i++)
{
list.Add(rand.Next(, ));
}
} private static void PrintList(List<int> list)
{
foreach (int element in list)
{
Console.Write ("{0, 5}", element);
}
Console.WriteLine();
}
}
}

运行结果:

【C#】Random类中构造方法、时间种子与随机数序列的关系

2) Random random = new Random(Int32); // 参数化构造函数使用指定的种子值初始化Random类实例,如果指定的是负数,则使用其绝对值作为时间种子。

创建随时间推移,时间种子取值范围大的 Random 对象,以确保生成多个Random对象时,彼此间的随机数序列不同。

  • 通常情况下使用计时周期数(Ticks)作为时间种子:

Random random = new Random((int)DateTime.Now.Ticks);

运行结果:

【C#】Random类中构造方法、时间种子与随机数序列的关系

  • 或者,通过加密随机数生成器(RNG)生成时间种子:
 Random random = new Random(GetRandomSeed());

 static int GetRandomSeed()
{
byte[] bytes = new byte[];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, );
}

运行结果:

【C#】Random类中构造方法、时间种子与随机数序列的关系