Why can't I cast from Action to DispatchedHandler?

不羁的心 提交于 2021-02-11 14:59:53

问题


G'day Folks,

I feel like I'm can't see something basic.

Action is defined as public delegate void Action().

DispatchedHandler is defined as public delegate void DispatchedHandler().

Yet the following code generates at the RunASync line: Error CS1503 Argument 2: cannot convert from 'System.Action' to 'Windows.UI.Core.DispatchedHandler'.

public static async Task DispatchToUI(Action action, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal )
{
    if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
    {
        action();
    }
    else
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( priority, action );
    }
}

Adding an explicit conversion thus:

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( priority, (DispatchedHandler)action ); 

fails with Error CS0030 Cannot convert type 'System.Action' to 'Windows.UI.Core.DispatchedHandler'.

So one version of public delegate void() can't convert to a different version of public delegate void()?


回答1:


You cannot convert a delegate like that, check this SO question.

You can, however, create a new delegate from the existing one:

public static async Task DispatchToUI(Action action, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
    if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
    {
        action();
    }
    else
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(priority, new DispatchedHandler(action));
    }
}


来源:https://stackoverflow.com/questions/52951664/why-cant-i-cast-from-action-to-dispatchedhandler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!