日期:2014-05-17  浏览次数:20899 次

求大神来看看这段代码哪里错了
private void timer4_Tick(object sender, EventArgs e)
        {
            int a = 0;
            Random q = new Random();
            a += (q.Next(1));
            if (button1.Location.X==60||button4.Location.Y==80)
            {
                timer5.Enabled = true;
            }
        }

        private void timer5_Tick(object sender, EventArgs e)
        {
            if (a == 0)
            {
                button1.visible = true
            }
            else
            {
                button1.Top += 20;
为什么每次这段代码都是执行else,怎么才能让他执行a=0时button1.visible=true
C#求助

------解决方案--------------------
引用:
Quote: 引用:

你的代码中,timer4_Tick中的a是局部变量,在timer5_Tick中是不存在的。要想在timer5_Tick用到timer4_Tick中的a,那就把a定义为全局变量。否则你的timer5_Tick是未定义的,所以一直都是执行else
C#的全局变量怎么设?能不能举个例子

 在你的 timer4_Tick和 timer5_Tick方法外定义一个变量a,这样两个地方都可以用了。比如在窗体类下添加一个字段a,那么类里面所有方法都可以使用。
    public partial class Form1 : Form
    {
        public int a;  //这个类下面的方法都可以使用
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //可以使用a
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
         &nb