The Random class constructor
1) random random = new random (); //Parameterless constructor uses the system clock to generate its seed value
However, the range of system clock values is limited , so in small-scale calculations, it may not be possible to call this constructor with different seed values, which will result in two random objects generating the same number sequence.
1 usingSystem;2 usingSystem.Collections.Generic;3 4 namespacefirsttest5 {6 class Program7 {8 Static voidMain (string[] args)9 {TenRandom random1 =NewRandom (); Onelist<int> List1 =Newlist<int>(); A getrandomnumbers (random1, list1); -Console.WriteLine ("the Random1 object uses the default constructor to generate a sequence of random numbers:"); - printlist (list1); the -Random random2 =NewRandom (); -list<int> List2 =Newlist<int>(); - getrandomnumbers (Random2, list2); +Console.WriteLine ("the Random2 object uses the default constructor to generate a sequence of random numbers:"); - printlist (list2); + } A at Private Static voidGetrandomnumbers (Random rand, list<int>list) - { - for(inti =1; I <= the; i++) - { -List. ADD (Rand. Next (0, -)); - } in } - to Private Static voidPrintlist (list<int>list) + { - foreach(intElementinchlist) the { *Console.Write ("{0, 5}", Element); $ }Panax Notoginseng Console.WriteLine (); - } the } +}
Operation Result:
2) random random = new Random (Int32); The //parameterized constructor initializes the random class instance with the specified seed value and, if a negative number is specified, uses its absolute value as the time seed.
Create random objects that have a large range of time seed values over time to ensure that when you generate several random objects, there is a difference in the sequence of numbers between each other.
- Typically, the number of ticks (Ticks) is used as the time seed:
1 random random = new random ((int) DateTime.Now.Ticks);
Operation Result:
- Alternatively, the time seed is generated by the cryptographic random number generator (RNG):
1Random random =NewRandom (Getrandomseed ());2 3 Static intgetrandomseed ()4 {5 byte[] bytes =New byte[4];6System.Security.Cryptography.RNGCryptoServiceProvider rng =NewSystem.Security.Cryptography.RNGCryptoServiceProvider ();7 rng. GetBytes (bytes);8 returnBitconverter.toint32 (Bytes,0);9}
Operation Result:
The relationship between the construction method, the time seed and the sequence of random numbers in the "C #" Random class