简体   繁体   中英

Cannot convert lambda expression to type 'System.Delegate' while Invoke

I get Cannot convert lambda expression to type 'System.Delegate' error while:

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

I looked up all posts about it, but i couldn't figure out/understand why? and the answers didnt solve my problem as well.

Lambda expressions cannot be cast to Delegate directly. However, if the method expects a delegate of a certain type (eg Action ), then you can use the lambda expression without casting. For example, in .Net 4.5 there exists a overload of:

public void Invoke(Action callback,DispatcherPriority priority)

this means you can do this:

this.Dispatcher.Invoke(() =>
        {
            //...
        }, DispatcherPriority.Background);

but that overload does not exist in .Net 4 or prior. So you would have to cast to an Action :

this.Dispatcher.Invoke((Action)(() =>
    {
        ...
    }), DispatcherPriority.Background); 

Note that I removed the new object[0] . It's not needed as Action doesn't take any parameters.

Don't cast to Delegate but to Action :

this.Dispatcher.Invoke((Action)(() =>
        {
            ...
        }), DispatcherPriority.Background, new object[0]);

you don't need to cast to delegate lambda expression implicitly casted by the compiler to a delegate type

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM