我遇到了一个很怪的问题,我在timer1_Tick事件里边写了生成随机数的函数rand.Next (1, 3),并将每次生成的随机数按顺序保存到一个数组里边。比如,在timer1运行了四次后我停止了timer1的运行,然后依次生成了1 2 2 1 这四个随机数,可是数组显示的结果是1 1 2 2 2 2 1 1,很奇怪,哪位高手能帮我解答呢?code如下:namespace wo_jiu_bu_xin_le
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
} ArrayList module4_array = new ArrayList(); private void timer1_Tick(object sender, EventArgs e)
{
Random rand = new Random();
int T = rand.Next(1, 3);
this.textBox1.Text = Convert.ToString(T);
module4_array.Add(T);
} private void button1_Click(object sender, EventArgs e)
{
timer1.Dispose();
foreach (int x in module4_array)
{
textBox2.Text = textBox2.Text + x + "\r\n";
}
}
}
}
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
} ArrayList module4_array = new ArrayList(); private void timer1_Tick(object sender, EventArgs e)
{
Random rand = new Random();
int T = rand.Next(1, 3);
this.textBox1.Text = Convert.ToString(T);
module4_array.Add(T);
} private void button1_Click(object sender, EventArgs e)
{
timer1.Dispose();
foreach (int x in module4_array)
{
textBox2.Text = textBox2.Text + x + "\r\n";
}
}
}
}
这句代码你在其他地方也运行了,导致事件绑定了2次,那就是2*4=8了。
我估计你在这里已经执行过绑定了,就是你添加timer的时候已经设置过它的相关属性,然后又手工去写了。
另外你是怎么知道只生成了1 2 2 1这4个随机数的?private void timer1_Tick(object sender, EventArgs e)
{
Random rand = new Random();
int T = rand.Next(1, 3);
this.textBox1.Text = Convert.ToString(T);
module4_array.Add(T);
Console.WriteLine(T.ToString());// 看output实际生成的数
}
我在timer1_Tick事件里边加入了声音提示,每运行一次就会响一下,响够四下后,我立刻按stop按钮,另外textBox1也可以用来监控。你看,结果本来是1 2 2 1,但array所显示的是1122 2211,仔细观察你会发现,这四个数字每个都重复了两次:1 2 2 1 vs 1 1 2 2 2 2 1 1。
你把
public Form1()
{
InitializeComponent(); //在这个方法中应该有timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
//timer1.Tick += new EventHandler(timer1_Tick); 这句去掉估计时间事件还会运行
timer1.Enabled = true;
}
int T = rand.Next(1, 3);
是会是1和2
ArrayList module4_array = new ArrayList(); 代码就是一直生成1或2 放到 module4_array 里..
BUTTON1 显示 module4_array 所有内容.
我删掉后timer1.Tick += ...后就可以了!真让人啼笑皆非阿。