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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14380996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:39:59  来源:igfitidea点击:

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type?

c#wpfdelegates

提问by Niels

I'm having a problem that I can't seem to figure out, although its kind of a standard question here on Stackoverflow.

我遇到了一个我似乎无法弄清楚的问题,尽管它是 Stackoverflow 上的一个标准问题。

I'm trying to update my Bing Maps asynchronously using the following code (mind you, this is from an old Silverlight project and does not seem to work in WPF)

我正在尝试使用以下代码异步更新我的 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));
    }
});

What am I doing wrong?

我究竟做错了什么?

采纳答案by Jean Hominal

You have to cast it explicitly to a Actionin order for the conversion to System.Delegateto kick in.

您必须将其显式Action转换为 aSystem.Delegate才能启动转换。

That is:

那是:

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

回答by SLaks

The BeginInvoke()method's parameter is the base Delegateclass.

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

You can only convert a lambda expression to a concrete delegate type.

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

To fix this issue, you need to explicitly construct a delegate:

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

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

回答by Alex

Try

尝试

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

Or use Action

或者使用动作