2013-03-09 219 views
3

`我想要在静态方法中更改文本框文本。我怎么能这样做,考虑到我不能在静态方法中使用“this”关键字。换句话说,我怎样才能使一个对象引用文本框的文本属性?非静态字段,方法或属性'member'需要对象引用

这是我的代码

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    public delegate void myeventhandler(string newValue); 


    public class EventExample 
    { 
     private string thevalue; 

     public event myeventhandler valuechanged; 

     public string val 
     { 
      set 
      { 
       this.thevalue = value; 
       this.valuechanged(thevalue); 

      } 

     } 

    } 

     static void func(string[] args) 
     { 
      EventExample myevt = new EventExample(); 
      myevt.valuechanged += new myeventhandler(last); 
      myevt.val = result; 
     } 

    public delegate string buttonget(int x); 



    public static buttonget intostring = factory; 

    public static string factory(int x) 
    { 

     string inst = x.ToString(); 
     return inst; 

    } 

    public static string result = intostring(1); 

    static void last(string newvalue) 
    { 
    Form1.textBox1.Text = result; // here is the problem it says it needs an object reference 
    } 



    private void button1_Click(object sender, EventArgs e) 
    { 
     intostring(1); 

    }` 
+3

请向我们展示您正在使用的代码。 – 2013-03-09 22:32:02

回答

3

如果你想从一个静态方法内改变非静态对象的属性,你需要在几种方法之一获取对对象的引用:

  • 该对象作为参数传递给您的方法 - 这是最常见的。该对象是你的方法的参数,你调用方法/设置属性
  • 该对象设置在一个静态字段 - 这对单线程程序是可以的,但它很容易出错,当你处理并发
  • 目的是可以通过一个静态引用 - 这是第二种方式的概括:该对象可以是,你可以运行从你的名字得到一个对象的静态注册表或其他一些ID等

在任何情况下,您的静态方法m ust获取对该对象的引用以检查其非静态属性或调用其非静态方法。

0

你从dasblinkenlight得到了一个完美的答案。这里是第三种方法的一个例子:

public static string result = intostring(1); 

static void last(string newvalue) 
{ 
    Form1 form = (Form1)Application.OpenForms["Form1"]; 
    form.textBox1.Text = result; 
} 

我不完全确定你为什么传递一个字符串参数,但不使用它。

+0

我试过了。它不会给出任何错误。但为什么结果的值没有显示在文本框中?你能给我第一种方法的例子吗? – user1853846 2013-03-09 23:51:11

+0

@ user1853846'intostring(1);'必须有错误。我真的不明白你从哪里得到字符串。 – AbZy 2013-03-09 23:55:00

相关问题