因为Invoke
/BeginInvoke
接受Delegate
(而不是一个类型的代表),你需要告诉编译器什么类型的委托创建的; (2.0)或Action
(3.5)是常用选项(注意它们具有相同的签名);像这样:
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});
如果您需要在参数中传递,然后在“捕捉变量”的方式:
string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});
(警告:你需要有点谨慎,如果使用捕获异步但同步是精 - 即上面是细)
另一种选择是写一个扩展方法:
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
则:
this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });
当然你也可以做同样的BeginInvoke
:
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
如果您不能使用C#3.0中,你可以做同样的一个普通实例方法,大概在Form
基类。
怎样才能我在这个答案中传递参数给你的第一个解决方案?我的意思是这个解决方案:control.Invoke((MethodInvoker)delegate {this.Text =“Hi”;}); – uzay95 2009-11-26 14:05:56