C# 调用时无法将lambda表达式转换为类型“System.Delegate”

C# 调用时无法将lambda表达式转换为类型“System.Delegate”,c#,invoke,dispatcher,C#,Invoke,Dispatcher,我无法将lambda表达式转换为类型“System.Delegate”错误,同时: this.Dispatcher.Invoke((Delegate)(() => { this.Focus(); if (!moveFocus) return; this.MoveFocus(new TraversalRequest(FocusNavi

我无法将lambda表达式转换为类型“System.Delegate”错误,同时:

this.Dispatcher.Invoke((Delegate)(() =>
            {
                this.Focus();
                if (!moveFocus)
                    return;
                this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }), DispatcherPriority.Background, new object[0]);
我查阅了所有关于它的帖子,但我不明白为什么?答案也不能解决我的问题。

不要向委托人施压,而是向行动施压:

不要强制转换为委托,而是转换为操作:


您不需要将编译器隐式转换为委托类型的lambda表达式转换为委托

this.Dispatcher.Invoke(() =>
            {
                this.Focus();
                if (!moveFocus)
                    return;
                this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }, DispatcherPriority.Background);

您不需要将编译器隐式转换为委托类型的lambda表达式转换为委托

this.Dispatcher.Invoke(() =>
            {
                this.Focus();
                if (!moveFocus)
                    return;
                this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }, DispatcherPriority.Background);

Lambda表达式不能直接转换为委托。但是,如果该方法需要某种类型的委托,例如Action,则可以使用lambda表达式,而无需强制转换。例如,在.Net 4.5中,存在以下过载:

public void Invoke(Action callback,DispatcherPriority priority)
这意味着您可以执行以下操作:

this.Dispatcher.Invoke(() =>
        {
            //...
        }, DispatcherPriority.Background);
但这种重载在.NET4或更早版本中并不存在。因此,你必须采取行动:


请注意,我删除了新对象[0]。由于操作不采用任何参数,因此不需要使用它。

Lambda表达式不能强制转换为直接委托。但是,如果该方法需要某种类型的委托,例如Action,则可以使用lambda表达式,而无需强制转换。例如,在.Net 4.5中,存在以下过载:

public void Invoke(Action callback,DispatcherPriority priority)
这意味着您可以执行以下操作:

this.Dispatcher.Invoke(() =>
        {
            //...
        }, DispatcherPriority.Background);
但这种重载在.NET4或更早版本中并不存在。因此,你必须采取行动:


请注意,我删除了新对象[0]。它不需要,因为动作不需要任何参数。

好吧,这很奇怪,因为当我使用新动作时,它也不起作用,但动作起作用了!!无论如何,请解释为什么不使用委托?新操作也会这样做。在这里也可以工作:Invokenew Action=>。您可以编写一些扩展方法来允许Invoke=>工作。我知道它应该可以工作,但它不工作,可能有错误/需要重新启动。是的,我可以,但没必要,只是sameOk很奇怪,因为当我使用新动作时,它也不起作用,但动作起作用了!!无论如何,请解释为什么不使用委托?新操作也会这样做。在这里也可以工作:Invokenew Action=>。您可以编写一些扩展方法来允许Invoke=>工作。我知道它应该可以工作,但它不工作,可能有错误/需要重新启动。是的,我可以,但不需要。这只是因为sameDoesn不起作用:无法将lambda表达式转换为“System.Delegate”类型,因为它不是委托类型。如果省略新对象[0],则可以这是没有道理的here@ErenErsönmez这是真的,我想OP实际使用的东西不起作用:无法将lambda表达式转换为类型“System.Delegate”,因为它不是委托类型是的,如果省略新对象[0],它会这是没有道理的here@ErenErsönmez这是真的,我想OP实际使用的是解释得很好的Eren:+1解释得很好的Eren:+1