Dispatcher.BeginInvoke:无法转换lambda来System.Delegate [英] Dispatcher.BeginInvoke: Cannot convert lambda to System.Delegate

查看:202
本文介绍了Dispatcher.BeginInvoke:无法转换lambda来System.Delegate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用 System.Windows.Threading.Dispatcher.BeginInvoke 。该方法的签名是这样的:

I'm trying to call System.Windows.Threading.Dispatcher.BeginInvoke. The signature of the method is this:

BeginInvoke(Delegate method, params object[] args)

我想通过它,而不必创建一个委托一个lambda。

I'm trying to pass it a Lambda instead of having to create a Delegate.

_dispatcher.BeginInvoke((sender) => { DoSomething(); }, new object[] { this } );

这是给我一个编译器错误,说我不能在lambda转换为System.Delegate。委托的​​签名需要一个对象作为参数并返回void。我的lambda匹配这个,但它不工作。我缺少什么?

It's giving me a compiler error saying that I can't convert the lambda to a System.Delegate. The signature of the delegate takes an object as a parameter and returns void. My lambda matches this, yet it's not working. What am I missing?

推荐答案

由于该方法需要一个 System.Delegate ,你需要给它一个特定类型的委托,声明等。这可以通过铸造或通过创造新的DelegateType指定的委托来完成如下:

Since the method takes a System.Delegate, you need to give it a specific type of delegate, declared as such. This can be done via a cast or a creation of the specified delegate via new DelegateType as follows:

_dispatcher.BeginInvoke(
     new Action<MyClass>((sender) => { DoSomething(); }),
     new object[] { this } 
  );

此外,作为 SLaks 指出,的 Dispatcher.BeginInvoke 需要一个参数数组,所以你可以这样写:

Also, as SLaks points out, Dispatcher.BeginInvoke takes a params array, so you can just write:

_dispatcher.BeginInvoke(
     new Action<MyClass>((sender) => { DoSomething(); }),
     this
  );

或者,如果DoSomething的是对象本身的一个方法:

Or, if DoSomething is a method on this object itself:

_dispatcher.BeginInvoke(new Action(this.DoSomething));

这篇关于Dispatcher.BeginInvoke:无法转换lambda来System.Delegate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆