How to randomly fill checkboxes in c# - Visual Studio
本问题已经有最佳答案,请猛点这里访问。
所以这是关于栈溢出的第一个问题。我正在研究一个鼓音序器,我想实现一个按钮来随机填充80个复选框,这些复选框指示正在触发鼓的声音。目前,我只有一个80随机填充框,但我希望每个都有一个随机填充的机会。我的代码的第一部分只是清除当前选择。以下代码是我的尝试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | private void button4_Click(object sender, EventArgs e) { List<CheckBox> Checkboxlist = new List<CheckBox>(); foreach (CheckBox control in this.Controls.OfType<CheckBox>()) { Checkboxlist.Add(control); control.Checked = false; } for (int i = 0; i <= 200; i++) { var random = new Random(); var r = random.Next(0, Checkboxlist.Count); var checkbox = Checkboxlist[r]; checkbox.Checked = true; } } |
谢谢你的关注!
不要在循环内创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | private static Random random = new Random(); // Class member private void button4_Click(object sender, EventArgs e) { List<CheckBox> Checkboxlist = new List<CheckBox>(); foreach (CheckBox control in this.Controls.OfType<CheckBox>()) { Checkboxlist.Add(control); control.Checked = false; } for (int i = 0; i <= 200; i++) { var r = random.Next(0, Checkboxlist.Count); var checkbox = Checkboxlist[r]; checkbox.Checked = true; } } |
原因是:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value,
来源
快速for循环使用相同的种子创建随机数,因此
您应该将随机声明移出for循环:
1 2 3 4 5 6 7 |
要在所有情况下遍历并更改为随机值,这可能适用于您。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private void button4_Click(object sender, EventArgs e) { List<CheckBox> Checkboxlist = new List<CheckBox>(); foreach (CheckBox control in this.Controls.OfType<CheckBox>()) { Checkboxlist.Add(control); control.Checked = false; } Random r = new Random(); int g = 0; for ( int i = 0; i < Checkboxlist.Length; i++){ g = r.Next(0,1); if(g ==1) Checkboxlist[i].Checked = true; } } |