时间:2022-11-01 09:20:03 | 栏目:.NET代码 | 点击:次
System.Random r = new Random(); s1 = r.NextDouble().ToString();//0.868992506465405 s2 = r.Next().ToString(); //1665548020 s3 = r.Next(10).ToString(); //5 s4 = r.Next(1000, 2000).ToString();//1885 byte[] buffer = new byte[255]; r.NextBytes(buffer); s5 = buffer[254].ToString(); ;//207
时间间隔如果太短,创建的多个不同的Ramdom对象将具有相同的默认种子值,因而会产生几组相同的随机数。
System.Random r1 = new Random(); System.Random r2 = new Random(); Console.WriteLine(r1.Next().ToString());// 615672499 Console.WriteLine(r2.Next().ToString());// 615672499
使用单个Random对象生成所有随机数可避免此问题。
System.Random r = new Random(); Console.WriteLine(r.Next().ToString());// 1933637733 Console.WriteLine(r.Next().ToString());// 1799552041
System.Random r1 = new Random(1); System.Random r2 = new Random(1); System.Random r3 = new Random(2); byte[] buffer1 = new byte[2]; byte[] buffer2 = new byte[2]; byte[] buffer3 = new byte[2]; r1.NextBytes(buffer1); r2.NextBytes(buffer2); r3.NextBytes(buffer3); s1 = String.Join(",", buffer1);// 70,208 s2 = String.Join(",", buffer2);// 70,208 s3 = String.Join(",", buffer3);// 113,147