我在 C# 中生成随机数时遇到问题。如果我RUN直接使用此表单应用,随机数生成对于所有人都是相同的。
If i DEBUG逐行按F10,就会产生不同的随机数。为什么会发生这种情况?我应该怎么做才能生成不同的随机数?
灰狗.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
class Greyhound
{
int location=0;
Random randomize = new Random();
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
public partial class Form1 : Form
{
Greyhound[] greyHound = new Greyhound[4];
ProgressBar[] progressBar = new ProgressBar[4];
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
greyHound[i] = new Greyhound();
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 3; i++)
{
progressBar[i].Value = greyHound[i].run();
}
}
}
}
不要实例化一个新的Random
每次对象,而不是将其用作static
member:
class Greyhound
{
static Random randomize = new Random();
int location=0;
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
See Random.Next 始终返回相同的值 https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)