`我想用静态方法更改文本框文本。考虑到我不能在静态方法中使用“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);
}`
最佳答案
如果您想从静态方法内部更改非静态对象的属性,您需要通过以下几种方式之一获取对该对象的引用:
- 对象作为参数传递给您的方法 - 这是最常见的。该对象是您的方法的参数,您可以在其上调用方法/设置属性
- 对象设置在静态字段中 - 这个对于单线程程序是可以的,但是当你处理并发时就容易出错
- 对象通过静态引用可用 - 这是第二种方式的概括:对象可能是单例,您可能正在运行静态注册表您可以通过名称或其他 ID 等获得对象。
在任何情况下,您的静态方法都必须获取对象的引用,以便检查其非静态属性或调用其非静态方法。
关于c# - 非静态字段、方法或属性需要对象引用 'member',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316651/