Invoke 调用中的匿名方法 [英] Anonymous method in Invoke call
问题描述
在我们想在 Control.Invoke 中匿名调用委托的语法上有一些问题.
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.
我们尝试了许多不同的方法,但都无济于事.
We have tried a number of different approaches, all to no avail.
例如:
myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
其中 someParameter 是此方法的本地
where someParameter is local to this method
以上会导致编译错误:
无法将匿名方法转换为类型System.Delegate",因为它不是委托类型
Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
推荐答案
因为 Invoke
/BeginInvoke
接受 Delegate
(而不是类型化的委托)),你需要告诉编译器创建什么类型的委托;MethodInvoker
(2.0) 或 Action
(3.5) 是常见的选择(注意它们有相同的签名);像这样:
Because Invoke
/BeginInvoke
accepts Delegate
(rather than a typed delegate), you need to tell the compiler what type of delegate to create ; MethodInvoker
(2.0) or Action
(3.5) are common choices (note they have the same signature); like so:
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});
如果需要传入参数,那么捕获的变量"是这样的:
If you need to pass in parameters, then "captured variables" are the way:
string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});
(警告:如果使用捕获async,你需要有点谨慎,但sync 很好 - 即上面的很好)
(caveat: you need to be a bit cautious if using captures async, but sync is fine - i.e. the above is fine)
另一种选择是编写扩展方法:
Another option is to write an extension method:
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
做同样的事情:
You can of course do the same with BeginInvoke
:
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
如果您不能使用 C# 3.0,您可以使用常规实例方法执行相同的操作,大概在 Form
基类中.
If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a Form
base-class.
这篇关于Invoke 调用中的匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!