我在c#中生成随机数问题.如果我直接运行此表单应用程序,则随机数生成对所有人来说都是相同的.
如果我通过按F10逐行调试,那么它将生成不同的随机数.为什么会这样?我该怎么做才能生成不同的随机数?
Greyhound.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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
ken*_*n2k 10
不要Random每次都实例化一个新对象,而是将其用作static成员:
class Greyhound
{
static Random randomize = new Random();
int location=0;
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
Run Code Online (Sandbox Code Playgroud)