2016-07-17 34 views
-1

我試圖讓這段代碼隨機選取4個鍵,然後使用'foreach'循環將它們寫入控制檯。它不是爲每次迭代挑選一個隨機選擇,而是隨機選擇一個鍵並將其寫入控制檯4次。這裏是代碼:爲什麼此方法只會隨機化一次,而不是隨機化每次迭代?

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 

namespace ListPractice 
{ 
    public class DictionaryData 
    {   
     public static void GetRandomKey() 
     { 
      Dictionary<string, int[]> QandA_Dictionary = new Dictionary<string, int[]>(); 
      QandA_Dictionary.Add("What is 1 + 1?", new int[] { 1, 2, 3, 4 }); 
      QandA_Dictionary.Add("What is 1 + 2?", new int[] { 1, 2, 3, 4 }); 
      QandA_Dictionary.Add("What is 1 + 3?", new int[] { 1, 2, 3, 4 }); 
      QandA_Dictionary.Add("What is 1 + 4?", new int[] { 2, 3, 4, 5 }); 

      List<string> keys = new List<string>(QandA_Dictionary.Keys); 

      foreach (var element in keys) 
      { 
       Random rand = new Random(); 
       string randomKey = keys[rand.Next(keys.Count)]; 
       Console.WriteLine(randomKey); 
      } 
      Console.ReadKey(); 
     } 

     public static void Main(string[] args) 
     { 
      GetRandomKey(); 
     } 

    } 
} 

回答

1

它隨機化一次,因爲你不斷創建一個Random類的新實例。每次初始化沒有種子的Random類的實例時,它將自動使用時鐘的當前滴答計數作爲其種子。由於循環通常迭代的速度有多快,它將在一到幾毫秒內完成,這意味着您的Random幾乎總是具有相同的種子。

聲明的Random你的循環每次使用它的時候會導致種子的變化,因此你不會在得到相同號碼一遍又一遍:

Random rand = new Random(); 
foreach (var element in keys) 
{ 
    string randomKey = keys[rand.Next(keys.Count)]; 
    Console.WriteLine(randomKey); 
} 
+0

這是相當有趣。我仍在學習。謝謝你的幫助。 – sean

+0

@sean:沒問題,我很高興能幫助你!還有更多信息需要閱讀[**有關它的MSDN文檔**](https://msdn.microsoft.com/en-us/library/h343ddh9(v = vs.110).aspx)。 –