2013-03-09 206 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

相關問題