我试图让这段代码随机挑出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();
}
}
}
答案 0 :(得分:1)
随机化一次,因为您不断创建Random
类的新实例。每次初始化没有种子的Random
类的实例时,它将自动使用时钟的当前刻度计数作为其种子。由于循环通常迭代的速度有多快,它将在一到几毫秒内完成,这意味着你的Random
几乎总是会有相同的种子。
在您的循环中声明Random
外部将导致每次使用时都会更改种子,因此您不会一遍又一遍地获得相同的数字:< / p>
Random rand = new Random();
foreach (var element in keys)
{
string randomKey = keys[rand.Next(keys.Count)];
Console.WriteLine(randomKey);
}