问题描述
有一点麻烦,我们要调用一个匿名委托一个Control.Invoke中的语法。
我们已经尝试了许多不同的方法,都没有用。
例如:
myControl.Invoke(委托(){的MyMethod(这一点,新MyEventArgs(someParameter));});
在这里someParameter是本地的这种方法
以上将导致一个编译器错误:
由于调用
/ 的BeginInvoke
接受代理
(而不是类型化的代表),你需要告诉编译器是什么类型的委托创建; MethodInvoker
(2.0)或者动作
(3.5)是常见的选择(注意,它们具有相同的签名);像这样:
control.Invoke((MethodInvoker)委托{this.Text =你好;});
如果你需要传递的参数,然后在捕获变量的方式:
字符串消息=你好;
control.Invoke((MethodInvoker)委托{this.Text =消息;});
(警告:您的需要,如果使用捕获的异步的,但是的同步的是罚款有点谨慎 - 即上面是罚款)
另一种方法是编写一个扩展方法:
公共静态无效的调用(该控制的控制,操作动作)
{
control.Invoke((代表)的动作);
}
然后:
this.Invoke(委托{this.Text =喜;});
//或者由于我们使用C#3.0
this.Invoke(()=> {this.Text =喜;});
您当然可以做同样的的BeginInvoke
:
公共静态无效的BeginInvoke(该控制的控制,操作动作)
{
control.BeginInvoke((代表)的动作);
}
如果您不能使用C#3.0,你可以用一个常规的实例方法,presumably在表格
基类做同样的。
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.
For example:
myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
where someParameter is local to this method
The above will result in a compiler error:
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;});
(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);
}
then:
this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });
You can of course do the same with BeginInvoke
:
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a Form
base-class.
这篇关于在调用调用匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!