简体   繁体   English

具有“ static”变量的C#textbox1_keydown事件

[英]C# textbox1_keydown event with “static” variable

Hi I just wrote a method for keydown event of a textbox. 嗨,我刚刚写了一个文本框的keydown事件的方法。 The problem here is: I need a variable to be "static", that is, the change of the variable could be reserved for the next run of the method. 这里的问题是:我需要一个变量是“静态的”,也就是说,变量的更改可以保留给方法的下一次运行。 I tried to use static but it seems only static method could allow such declaration. 我尝试使用static,但似乎只有static方法可以允许这样的声明。

Can I ask what can I do to solve the problem? 我可以问该怎么做才能解决问题? Thank you very much! 非常感谢你!

private  void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {

        if (e.KeyCode != Keys.Enter) return;

        if (comboBox1.SelectedIndex == 0)
        {

            if (textBox1.Text == "00000000")
            {

                typeselected = true;
                type = 0;

            }
            else if (textBox1.Text == "00000001")
            {
                typeselected = true;
                type = 1;

            }
            else if (textBox1.Text == "00000002")
            {
                typeselected = true;
                type = 2;
            }
            else if (textBox1.Text == "00000003")
            {
                typeselected = true;
                type = 3;

            }
            else if (textBox1.Text == "00000004")
            {
                typeselected = true;
                type = 4;

            }
            else if (textBox1.Text == "00000005")
            {
                typeselected = true;
                type = 5;

            }
            else if (textBox1.Text == "00000006")
            {
                typeselected = true;
                type = 6;

            }


            else if (typeselected) { typeselected = excel0(textBox1.Text, type); }
        }

You could make use of an instance variable 您可以使用实例变量

An instance variable of a class comes into existence when a new instance of that class is created, and ceases to exist when there are no references to that instance and the instance's destructor (if any) has executed. 类的实例变量在创建该类的新实例时就存在,并且在没有对该实例的引用且该实例的析构函数(如果有)已执行时就不再存在。

Something like 就像是

private int tada = 0;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    tada++;
}

使您的静态变量成为类实例变量,而不是方法变量。

Instance methods (without the keyword static) can reference static class variables: 实例方法(没有关键字static)可以引用静态类变量:

class X
{
    static int A;

    public void SetA(int newA)
    {
        A = newA;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM