如何在静态方法中引用非静态对象

如何在静态方法中引用非静态对象

问题描述:

我已经创建了一个文本框并希望在静态方法中引用它。我怎样才能做到这一点? 这里;我的代码如何在静态方法中引用非静态对象

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 
    } 
+0

你不能。你需要一个对象。 – 2013-03-11 10:34:55

+2

另请注意,在您的代码中,Form1_Load中的textbox2是本地方法,而不是类。定义Textbox textbox2外Form1_Load – rene 2013-03-11 10:36:15

+0

http://*.com/questions/498400/an-object-reference-is-required-for-the-nonstatic-field-method-or-property-wi – 2013-03-11 10:36:15

你就需要把它传递到静态方法不知何故,最简单的选择是仅扩展方法签名接受文本框:

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

谢谢。有效。 – user1853846 2013-03-11 10:52:05

+0

@ user1853846不要忘记接受你认为是最好的答案(在这种情况下,劳埃德的) – Nolonar 2013-03-11 10:58:18

+1

@ user1853846如果你不知道如何接受答案,或为什么你应该这样做:http:// meta .stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Nolonar 2013-06-06 15:06:31

我不是确定你明白什么是静态的意思,静态意味着它属于CLASS而不是类的实例。可能对您的问题更好的解决方案是创建一个设置文本的实例方法。

// 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"; 
} 

如果您在理解static时遇到困难,您不需要使用它。静态成员可用于类的所有实例,但不属于它们中的任何一个,这意味着静态方法不能访问私有成员。

+1

为什么会得到低投票?它没有使用“静态”方法,但据我所知,这是一个完全有效的答案,我错过了什么? – Nolonar 2013-03-11 10:47:04

+1

也不知道为什么(它不是直接回答明确的问题,是的,但它肯定会给出什么可能是最好和最有用的答案,在我心中)+1 – baldric 2013-03-11 10:52:40

你应该给你的文本作为参数传递给静态方法

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

你可以这样做

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

而在代码

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

您可以创建一个静态变量载入:

private static readonly TextBox _textBox = new TextBox(); 

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

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

该文本框是只读的,永不重新分配,只有文本属性。如果您愿意,可以删除只读文件并在Load方法上创建文本框。 – Toto 2013-03-11 13:08:17