how to reference a non static object in a static method

牧云@^-^@ 提交于 2019-12-11 04:34:24

问题


I've created a textbox and want to reference it in a static methd. how can I do that? here;s my code

    private void Form1_Load(object sender, EventArgs e)
    {
        TextBox textbox2 = new TextBox();
        textbox2.Text = "A";
    }

    static void gettext() 
    {
        textbox2.Text = "B"; //here is my problem
    } 

回答1:


You would need to pass it into the static method somehow, easiest option is to just expand the method signature to accept the textbox:

static void gettext(TextBox textBox) 
{
    textBox.Text = "B"; //here is my problem
} 



回答2:


You should give your textbox as a parameter to the static method

static void gettext(TextBox textbox)
{
    textbox.Text = "B";
}



回答3:


I'm not sure you understand what static means, static means that it belongs to the CLASS not an INSTANCE of the class. Possibly a better solution to your problem would be to create an instance method which set the text.

// private variable
private TextBox textbox2;

private void Form1_Load(object sender, EventArgs e)
{
    // refers to private instance variable
    textbox2 = new TextBox();
    textbox2.Text = "A";
}

private void gettext() 
{
    // refers to private instance variable
    textbox2.Text = "B";
} 

If you're having difficulty understanding static, odds are you don't need to use it. Static members are available to all instances of a class but don't belong to any of them, which means static methods cannot access private members.




回答4:


You can do so

static void gettext(TextBox textbox2) 
{
    textbox2.Text = "B";
} 

And in code

private void Form1_Load(object sender, EventArgs e)
{
    YourClass.gettext(textbox2);
}



回答5:


You can create a static variable set on Load :

private static readonly TextBox _textBox = new TextBox();

private void Form1_Load(object sender, EventArgs e)
{
    _textBox.Text = "A";
}

static void gettext()  
{ 
    _textbox2.Text = "B";
} 


来源:https://stackoverflow.com/questions/15336369/how-to-reference-a-non-static-object-in-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!