gpt4 book ai didi

c# - 无法将类型 IAsyncOperation 隐式转换为 StorageFile

转载 作者:太空狗 更新时间:2023-10-30 01:06:05 25 4
gpt4 key购买 nike

我的代码到底出了什么问题?

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

它给我这个错误:

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

如果我添加 'await',就像在代码中评论的那样,我会收到以下错误:

¹ 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'.

代码源here

最佳答案

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

您只能使用 awaitasync方法...所以您可能想将方法更改为异步方法:

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# - 无法将类型 IAsyncOperation<StorageFile> 隐式转换为 StorageFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16512346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com