问题
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