无法将lambda表达式转换为类型’System.Delegate’,因为它不是委托类型?

我遇到了一个我似乎无法弄清楚的问题,虽然这是Stackoverflow上的一个标准问题。

我正在尝试使用以下代码异步更新我的Bing地图(请注意,这是来自旧的Silverlight项目,似乎不适用于WPF)

_map.Dispatcher.BeginInvoke(() => { _map.Children.Clear(); foreach (var projectedPin in pinsToAdd.Where(pin => PointIsVisibleInMap(pin.ScreenLocation, _map))) { _map.Children.Add(projectedPin.GetElement(ClusterTemplate)); } }); 

我究竟做错了什么?

您必须将其显式转换为Action才能转换为System.Delegate

那是:

 _map.Dispatcher.BeginInvoke((Action)(() => { _map.Children.Clear(); foreach (var projectedPin in pinsToAdd.Where(pin => PointIsVisibleInMap(pin.ScreenLocation, _map))) { _map.Children.Add(projectedPin.GetElement(ClusterTemplate)); } })); 

BeginInvoke()方法的参数是基本的Delegate类。

您只能将lambda表达式转换为具体的委托类型。

要解决此问题,您需要显式构造委托:

 BeginInvoke(new MethodInvoker(() => { ... })); 

尝试

 Dispatcher.BeginInvoke(new System.Threading.ThreadStart(delegate { //Do something })); 

或者使用Action