3

`我想以静态方法更改文本框文本。考虑到我不能在静态方法中使用“this”关键字,我该怎么做。换句话说,如何使对象引用文本框文本属性?

这是我的代码

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

    }`
4

2 回答 2

3

如果要从静态方法内部更改非静态对象的属性,则需要通过以下几种方式之一获取对该对象的引用:

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

在任何情况下,您的静态方法都必须获得对该对象的引用才能检查其非静态属性或调用其非静态方法。

于 2013-03-09T22:36:55.083 回答
0

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

public static  string result = intostring(1);

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

我不完全确定您为什么要传递字符串参数而不是使用它。

于 2013-03-09T22:46:21.750 回答