我利用timer1每隔1秒生成一个随机数int T = rand.Next(1, 3),并保存到数组arr里边,共生成6个数(用timer2来控制:timer2的Internal=6000),并在textBox1中显示arr。点击button1会触发timer1事件。如果在不关闭form的情况下,我想重复运行程序,也就是说再次点击button1,这样的话数组arr就会一直增加,比如第一次运行程序后,数组arr有6个元素,第二次运行后,数组arr就会有12个元素,我想要的是,不论点击多少次button1,数组arr始终都是6个,也就是说,程序运行第二次的时候,会自动把第一次运行得到的数组arr清空,运行第三次的时候,会把第二次的清空,请问这个怎么实现呢?具体code怎么编写呢?code 如下:
namespace yu_men
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); } ArrayList arr = new ArrayList();
Random rand = new Random(); private void timer1_Tick(object sender, EventArgs e)
{
timer2.Interval = 6 * 1000;
timer2.Enabled = true;
int T = rand.Next(1, 3);
textBox0.Text = Convert.ToString(T);
arr.Add(T);
} private void timer2_Tick(object sender, EventArgs e)
{
timer1.Dispose();
timer2.Dispose();
textBox0.Clear(); foreach (int x in arr)
{
textBox1.Text = textBox1.Text + x + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{ textBox1.Clear();
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{ }
}
}
namespace yu_men
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); } ArrayList arr = new ArrayList();
Random rand = new Random(); private void timer1_Tick(object sender, EventArgs e)
{
timer2.Interval = 6 * 1000;
timer2.Enabled = true;
int T = rand.Next(1, 3);
textBox0.Text = Convert.ToString(T);
arr.Add(T);
} private void timer2_Tick(object sender, EventArgs e)
{
timer1.Dispose();
timer2.Dispose();
textBox0.Clear(); foreach (int x in arr)
{
textBox1.Text = textBox1.Text + x + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{ textBox1.Clear();
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{ }
}
}
{
timer1.Dispose();
timer2.Dispose();
textBox0.Clear();
textBox1.Clear();
foreach (int x in arr)
{
textBox1.Text = textBox1.Text + x + "\r\n";
}
}
问题不是出在这里谢谢。问题出在数组arr本身,怎么能在点击button1后数组arr被初始化,然后重新赋值。我知道想法,但不知道具体怎么编写代码。谢谢了!