[英]Dispatcher.BeginInvoke: Cannot convert lambda to System.Delegate
我正在嘗試調用System.Windows.Threading.Dispatcher.BeginInvoke
。 該方法的簽名是這樣的:
BeginInvoke(Delegate method, params object[] args)
我正在嘗試將其傳遞給Lambda,而不必創建委托。
_dispatcher.BeginInvoke((sender) => { DoSomething(); }, new object[] { this } );
它給我一個編譯器錯誤,說我
無法將lambda轉換為System.Delegate。
委托的簽名將對象作為參數並返回void。 我的lambda與此匹配,但無法正常工作。 我想念什么?
由於該方法采用System.Delegate ,因此需要為其指定一種特定類型的委托,並聲明為此類。 可以通過強制轉換或通過新的DelegateType創建指定的委托來完成,如下所示:
_dispatcher.BeginInvoke(
new Action<MyClass>((sender) => { DoSomething(); }),
new object[] { this }
);
另外,正如SLaks指出的那樣, Dispatcher.BeginInvoke接受一個params數組,因此您可以編寫:
_dispatcher.BeginInvoke(
new Action<MyClass>((sender) => { DoSomething(); }),
this
);
或者,如果DoSomething是此對象本身的方法:
_dispatcher.BeginInvoke(new Action(this.DoSomething));
更短:
_dispatcher.BeginInvoke((Action)(() => DoSomething()));
如果從項目中引用System.Windows.Presentation.dll並using System.Windows.Threading
添加,則可以訪問允許使用lambda語法的擴展方法。
using System.Windows.Threading;
...
Dispatcher.BeginInvoke(() =>
{
});
使用內聯Lambda ...
Dispatcher.BeginInvoke((Action)(()=>{
//Write Code Here
}));
我們為此創建擴展方法。 例如
public static void BeginInvoke(this Control control, Action action)
=> control.BeginInvoke(action);
現在我們可以從以下形式調用它: this.BeginInvoke(() => { ... })
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.