C#变量不断被重新分配给初始值

时间:2016-11-28 00:45:00

标签: c# variables

我是C#的新手,正在开展一个小组项目,大部分代码都不是由我编写的。我正在尝试创建用于收集一系列数据的用户界面。在提出一个问题之后,我想要出现下一个问题。我通过分配一个变量' gesturenumber'来做到这一点。并且当用户输入“下一个”时,它会增加它。问题是值会一直返回到最初定义的值。

这是我在此功能开始时的初始化步骤:

public void CheckKeys(object sender,      System.Windows.Forms.KeyPressEventArgse)    enter code here{
        int gesturenumber = 0;
        int testnumber = 1;



        if (e.KeyChar == (char)13)
        {
            int totalLines = richTextBox1.Lines.Length;
            string lastLine = richTextBox1.Lines[totalLines - 2];               
            if (lastLine == "clear")
            {
                richTextBox1.Clear();
                richTextBox1.AppendText("Welcome\n\nTo connect an IMU, please enter it's three digit ID number\n\nFor Assistance - Enter \"help\"\n\n", true);

当用户输入'收集'此值应更改为1,并且当用户键入' next'它应该增加1.我写的代码如下:

if (lastLine == "collect")
            {

                richTextBox1.AppendText("\nThank you for volunteering for our data collection process\n");
                richTextBox1.AppendText("\nYou will be asked to carry out a series of gestures. Please repeat each gesture 10 times before moving on to the next.\n");
                richTextBox1.AppendText("\nPlease choose which gesture number you will be doing'\n");
                gesturenumber = 1;
                testnumber = testnumber + 1;

            }



            if (lastLine == "next")
            {
                gesturenumber = gesturenumber + 1;
                foreach (NU NU in ConnectedIMUS)
                {
                    NU.StopNU();
                    NU.saveData = false;
                    NU.Kat = false;

                }
                try
                {
                    file.Close();
                    richTextBox1.AppendText("\n Thank you for completing the gesture, please follow the instructions for the next gesture \n", true);
                }
                catch (Exception) { }
                richTextBox1.AppendText(" ", true);

            }

每个部分都包含在一个单独的if语句中,其中读取用户输入或读取某个变量。

当函数运行时,gesturenumber保持重置为零,不允许触发if语句。请帮我! 感谢

1 个答案:

答案 0 :(得分:0)

每次运行函数时都会重置变量,因为您在函数中设置了值

相反,将它们移到函数之外,使它们成为成员级字段:

private int gesturenumber = 0;
private int testnumber = 1;

public void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        ...