简体   繁体   English

无法将IAsyncOperation <StorageFile>类型隐式转换为StorageFile

[英]Cannot implicitly convert type IAsyncOperation<StorageFile> to StorageFile

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' 无法将类型'Windows.Foundation.IAsyncOperation'隐式转换为'Windows.Storage.StorageFile'

And if I add the 'await', like commented on the code, I get the following error: 如果我添加'await',就像在代码上发表评论一样,我收到以下错误:

¹ The 'await' operator can only be used within an async method. ¹“await”运算符只能在异步方法中使用。 Consider marking this method with the 'async' modifier and changing its return type to 'Task'. 考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'。

Code source here 代码源在这里

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. FileOpenPicker.PickSingleFileAsync返回IAsyncOperation<StorageFile> - 所以不,您不能将该返回值分配给StorageFile变量。 The typical way of using IAsyncOperation<> in C# is with await . 在C#中使用IAsyncOperation<>的典型方法是await

You can only use await in async methods... so you probably want to change your method to be asynchronous: 您只能在async方法中使用await ...因此您可能希望将方法更改为异步:

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. 请注意,除了事件处理程序之外的任何其他内容,最好使异步方法返回Task而不是void - 使用void的能力实际上只是因为您可以使用异步方法作为事件处理程序。

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. 如果你还不熟悉async / await ,你应该在进一步阅读之前阅读它 - MSDN“异步和等待异步编程”页面可能是一个不错的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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