Random類
構造函數
1) Random random = new Random(); // 無參數構造函數使用系統時鍾生成其種子值
然而,系統時鍾取值范圍有限,因此在小規模計算中,可能無法使用不同的種子值分別調用此構造函數, 這將導致兩個random對象生成相同的隨機數字序列。
1 using System; 2 using System.Collections.Generic; 3 4 namespace FirstTest 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 Random random1 = new Random(); 11 List<int> list1 = new List<int>(); 12 GetRandomNumbers(random1, list1); 13 Console.WriteLine("random1對象使用默認構造函數生成的隨機數序列: "); 14 PrintList(list1); 15 16 Random random2 = new Random(); 17 List<int> list2 = new List<int>(); 18 GetRandomNumbers(random2, list2); 19 Console.WriteLine("random2對象使用默認構造函數生成的隨機數序列: "); 20 PrintList(list2); 21 } 22 23 private static void GetRandomNumbers(Random rand, List<int> list) 24 { 25 for (int i = 1; i <= 15; i++) 26 { 27 list.Add(rand.Next(0, 100)); 28 } 29 } 30 31 private static void PrintList(List<int> list) 32 { 33 foreach (int element in list) 34 { 35 Console.Write ("{0, 5}", element); 36 } 37 Console.WriteLine(); 38 } 39 } 40 }
運行結果:
2) Random random = new Random(Int32); // 參數化構造函數使用指定的種子值初始化Random類實例,如果指定的是負數,則使用其絕對值作為時間種子。
創建隨時間推移,時間種子取值范圍大的 Random 對象,以確保生成多個Random對象時,彼此間的隨機數序列不同。
- 通常情況下使用計時周期數(Ticks)作為時間種子:
1 Random random = new Random((int)DateTime.Now.Ticks);
運行結果:
- 或者,通過加密隨機數生成器(RNG)生成時間種子:
1 Random random = new Random(GetRandomSeed()); 2 3 static int GetRandomSeed() 4 { 5 byte[] bytes = new byte[4]; 6 System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); 7 rng.GetBytes(bytes); 8 return BitConverter.ToInt32(bytes, 0); 9 }
運行結果: