Cannot implicitly convert type IAsyncOperation<StorageFile> to StorageFile

做~自己de王妃 提交于 2021-02-08 19:45:59

问题


What the hell is wrong with my code?

    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker FilePicker = new FileOpenPicker();
        FilePicker.FileTypeFilter.Add(".exe");
        FilePicker.ViewMode = PickerViewMode.List;
        FilePicker.SuggestedStartLocation = PickerLocationId.Desktop;
        // IF I PUT AWAIT HERE   V     I GET ANOTHER ERROR¹
        StorageFile file = FilePicker.PickSingleFileAsync();
        if (file != null)
        {
            AppPath.Text = file.Name;
        }
        else
        {
            AppPath.Text = "";
        }         
    }

It gives me this error:

Cannot implicitly convert type 'Windows.Foundation.IAsyncOperation' to 'Windows.Storage.StorageFile'

And if I add the 'await', like commented on the code, I get the following error:

¹ The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

Code source here


回答1:


Well, the reason your code doesn't compile is explained pretty directly by the compiler error message. FileOpenPicker.PickSingleFileAsync returns an IAsyncOperation<StorageFile> - so no, you can't assign that return value to a StorageFile variable. The typical way of using IAsyncOperation<> in C# is with await.

You can only use await in async methods... so you probably want to change your method to be asynchronous:

private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
    ...
    StorageFile file = await FilePicker.PickSingleFileAsync();
    ...
}

Note that for anything other than event handlers, it's better to make an async method return Task rather than void - the ability to use void is really only so you can use an async method as an event handler.

If you're not really familiar with async/await yet, you should probably read up on it before you go any further - the MSDN "Asynchronous Programming with async and await" page is probably a decent starting point.



来源:https://stackoverflow.com/questions/16512346/cannot-implicitly-convert-type-iasyncoperationstoragefile-to-storagefile

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