【问题标题】:Cannot cast IStorageItem to StorageFile无法将 IStorageItem 转换为 StorageFile
【发布时间】:2016-09-22 09:21:20
【问题描述】:

以下代码将无法编译,因为 IsOfType 不被接受为项上的方法。文档指出:

当这个方法成功完成时,它返回一个 IStorageItem 表示指定的文件或文件夹。如果指定的文件或 未找到文件夹,此方法返回 null 而不是引发 例外。

要处理返回的项目,请调用 IStorageItem 接口判断item是一个文件还是一个 文件夹。然后将该项目投射到 StorageFolder 或 StorageFile。

private async void RestoreData(string fileName)
    {
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        var item = folder.TryGetItemAsync(fileName);
        if (item == null)
        {
            existingData = false;
        }
        if (item.IsOfType(StorageItemTypes.File))
        {
            await ReadDataAsync(item as StorageFile);
            existingData = true;
        }
        existingData = false;
    }

【问题讨论】:

    标签: c# .net windows universal


    【解决方案1】:

    您缺少 await 关键字来等待异步方法的结果 - 在这种情况下,您应该编写如下内容:

    var item = await folder.TryGetItemAsync(fileName);
    

    感谢item 的类型为IStorageItem,而在您的代码中它的类型为IAsyncOperation<IStorageItem>

    convention,所有异步方法都有Async后缀,你需要等待结果来检查它。

    提示:

    在大多数 IDE 中,当您将鼠标悬停在 var 关键字上时,将显示一种变量类型 - 这样更容易找到错误。

    【讨论】:

    • 多哈。我确实注意到类型是 IAsyncOperation 但我没有意识到这是等待丢失的线索。
    • 很好,我可以帮忙。异步是 C# 中非常重要的一部分,我建议阅读它们 - MSDN page 涵盖了基础知识。
    猜你喜欢
    • 2013-05-06
    • 2017-02-06
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2015-09-04
    • 2016-05-26
    相关资源
    最近更新 更多