在不同的处理程序中更改变量

时间:2014-01-21 16:47:07

标签: visual-studio-2013

我正在创建变量和随机数,我无法从我的脚本中的其他处理程序访问它们。有没有办法让变量在我的所有事件处理程序中访问?我的表单处理程序中的我的整数不能在我的button1处理程序中编辑我的变量。请帮忙,谢谢

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IqTest


{


public partial class Form1 : Form
{





    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)

    {

        Random rand = new Random();
        int ran = rand.Next(70, 100);
        string mystring = ran.ToString();
        label2.Text = mystring;
    }

    private void checkBox11_CheckedChanged(object sender, EventArgs e)
    {
        int ran = 0;
    }








}

}

1 个答案:

答案 0 :(得分:0)

您可以将整数声明为类级别变量,然后两个事件处理程序都可以访问它。

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IqTest


{


public partial class Form1 : Form
{
    private int ran;


    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)

    {

        Random rand = new Random();
        ran = rand.Next(70, 100);
        string mystring = ran.ToString();
        label2.Text = mystring;
    }

    private void checkBox11_CheckedChanged(object sender, EventArgs e)
    {
        ran = 0;
    }

}
}