【问题标题】:Cannot implicitly convert type IAsyncOperation<StorageFile> to StorageFile无法将类型 IAsyncOperation<StorageFile> 隐式转换为 StorageFile
【发布时间】:2013-05-06 21:56:12
【问题描述】:

我的代码到底有什么问题?

    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 = "";
        }         
    }

它给了我这个错误:

无法将类型“Windows.Foundation.IAsyncOperation”隐式转换为“Windows.Storage.StorageFile”

如果我添加'await',就像对代码的注释一样,我会收到以下错误:

¹ 'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其返回类型更改为 'Task'。

代码源here

【问题讨论】:

    标签: c# microsoft-metro async-await filepicker storagefile


    【解决方案1】:

    好吧,编译器错误消息非常直接地解释了您的代码无法编译的原因。 FileOpenPicker.PickSingleFileAsync 返回 IAsyncOperation&lt;StorageFile&gt; - 所以不,您不能将该返回值分配给 StorageFile 变量。在 C# 中使用IAsyncOperation&lt;&gt; 的典型方式是使用await

    您只能在async 方法中使用await...所以您可能希望将您的方法更改为异步:

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

    请注意,对于事件处理程序以外的任何内容,最好让异步方法返回 Task 而不是 void - 使用 void 的能力实际上只是您可以使用作为事件处理程序的异步方法。

    如果您对async/await 还不是很熟悉,那么您可能应该在继续之前阅读它——MSDN "Asynchronous Programming with async and await" 页面可能是一个不错的起点。

    【讨论】:

    • 现在我明白了,非常感谢!我开始学习 C#,这个 async/await 东西对我来说真的很新鲜。非常感谢您的帮助!
    猜你喜欢
    • 2016-09-22
    • 2017-02-06
    • 1970-01-01
    • 2017-01-22
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多