簡體   English   中英

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

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

嗨,我剛剛寫了一個文本框的keydown事件的方法。 這里的問題是:我需要一個變量是“靜態的”,也就是說,變量的更改可以保留給方法的下一次運行。 我嘗試使用static,但似乎只有static方法可以允許這樣的聲明。

我可以問該怎么做才能解決問題? 非常感謝你!

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); }
        }

您可以使用實例變量

類的實例變量在創建該類的新實例時就存在,並且在沒有對該實例的引用且該實例的析構函數(如果有)已執行時就不再存在。

就像是

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

使您的靜態變量成為類實例變量,而不是方法變量。

實例方法(沒有關鍵字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